from typing import List, Optional
from sqlalchemy.orm import Session
from sqlalchemy import and_, or_, func, desc
from datetime import date, datetime
from app.models.local_flight import LocalFlight, LocalFlightStatus, LocalFlightType
from app.schemas.local_flight import LocalFlightCreate, LocalFlightUpdate, LocalFlightStatusUpdate
from app.models.journal import EntityType
from app.models.circuit import Circuit
from app.crud.crud_journal import journal


class CRUDLocalFlight:
    def get(self, db: Session, flight_id: int) -> Optional[LocalFlight]:
        return db.query(LocalFlight).filter(LocalFlight.id == flight_id).first()

    def get_multi(
        self, 
        db: Session, 
        skip: int = 0, 
        limit: int = 100,
        status: Optional[LocalFlightStatus] = None,
        flight_type: Optional[LocalFlightType] = None,
        date_from: Optional[date] = None,
        date_to: Optional[date] = None
    ) -> List[LocalFlight]:
        query = db.query(LocalFlight)
        
        if status:
            query = query.filter(LocalFlight.status == status)
        
        if flight_type:
            query = query.filter(LocalFlight.flight_type == flight_type)
        
        if date_from:
            query = query.filter(func.date(LocalFlight.created_dt) >= date_from)
            
        if date_to:
            query = query.filter(func.date(LocalFlight.created_dt) <= date_to)
        
        return query.order_by(desc(LocalFlight.created_dt)).offset(skip).limit(limit).all()

    def get_active_flights(self, db: Session) -> List[LocalFlight]:
        """Get currently active (booked out or departed) flights"""
        return db.query(LocalFlight).filter(
            or_(
                LocalFlight.status == LocalFlightStatus.BOOKED_OUT,
                LocalFlight.status == LocalFlightStatus.DEPARTED
            )
        ).order_by(desc(LocalFlight.created_dt)).all()

    def get_departures_today(self, db: Session) -> List[LocalFlight]:
        """Get today's departures (booked out or departed)"""
        today = date.today()
        return db.query(LocalFlight).filter(
            and_(
                func.date(LocalFlight.created_dt) == today,
                or_(
                    LocalFlight.status == LocalFlightStatus.BOOKED_OUT,
                    LocalFlight.status == LocalFlightStatus.DEPARTED
                )
            )
        ).order_by(LocalFlight.created_dt).all()

    def get_booked_out_today(self, db: Session) -> List[LocalFlight]:
        """Get all flights booked out today"""
        today = date.today()
        return db.query(LocalFlight).filter(
            and_(
                func.date(LocalFlight.created_dt) == today,
                or_(
                    LocalFlight.status == LocalFlightStatus.BOOKED_OUT,
                    LocalFlight.status == LocalFlightStatus.LANDED
                )
            )
        ).order_by(LocalFlight.created_dt).all()

    def create(self, db: Session, obj_in: LocalFlightCreate, created_by: str) -> LocalFlight:
        db_obj = LocalFlight(
            **obj_in.dict(),
            created_by=created_by,
            status=LocalFlightStatus.BOOKED_OUT
        )
        db.add(db_obj)
        db.commit()
        db.refresh(db_obj)
        return db_obj

    def update(self, db: Session, db_obj: LocalFlight, obj_in: LocalFlightUpdate, user: str = "system", user_ip: Optional[str] = None) -> LocalFlight:
        from datetime import datetime as dt
        
        update_data = obj_in.dict(exclude_unset=True)
        changes = []
        
        for field, value in update_data.items():
            old_value = getattr(db_obj, field)
            
            # Normalize datetime values for comparison (ignore timezone differences)
            if isinstance(old_value, dt) and isinstance(value, dt):
                # Compare only the date and time, ignoring timezone
                old_normalized = old_value.replace(tzinfo=None) if old_value.tzinfo else old_value
                new_normalized = value.replace(tzinfo=None) if value.tzinfo else value
                if old_normalized == new_normalized:
                    continue  # Skip if datetimes are the same
            
            if old_value != value:
                changes.append(f"{field} changed from '{old_value}' to '{value}'")
                setattr(db_obj, field, value)
        
        if changes:
            db.add(db_obj)
            db.commit()
            db.refresh(db_obj)
            
            # Log changes in journal
            for change in changes:
                journal.log_change(
                    db,
                    EntityType.LOCAL_FLIGHT,
                    db_obj.id,
                    change,
                    user,
                    user_ip
                )
        
        return db_obj

    def update_status(
        self, 
        db: Session, 
        flight_id: int, 
        status: LocalFlightStatus,
        timestamp: Optional[datetime] = None,
        user: str = "system",
        user_ip: Optional[str] = None
    ) -> Optional[LocalFlight]:
        db_obj = self.get(db, flight_id)
        if not db_obj:
            return None
        
        # Ensure status is a LocalFlightStatus enum
        if isinstance(status, str):
            status = LocalFlightStatus(status)
        
        old_status = db_obj.status
        db_obj.status = status
        
        # Set timestamps based on status
        current_time = timestamp if timestamp is not None else datetime.utcnow()
        if status == LocalFlightStatus.DEPARTED:
            db_obj.departed_dt = current_time
        elif status == LocalFlightStatus.LANDED:
            db_obj.landed_dt = current_time
            # Count circuits from the circuits table and populate the circuits column
            circuit_count = db.query(func.count(Circuit.id)).filter(
                Circuit.local_flight_id == flight_id
            ).scalar()
            db_obj.circuits = circuit_count
        
        db.add(db_obj)
        db.commit()
        db.refresh(db_obj)
        
        # Log status change in journal
        journal.log_change(
            db,
            EntityType.LOCAL_FLIGHT,
            flight_id,
            f"Status changed from {old_status.value} to {status.value}",
            user,
            user_ip
        )
        
        return db_obj

    def cancel(self, db: Session, flight_id: int) -> Optional[LocalFlight]:
        db_obj = self.get(db, flight_id)
        if db_obj:
            db_obj.status = LocalFlightStatus.CANCELLED
            db.add(db_obj)
            db.commit()
            db.refresh(db_obj)
        return db_obj


local_flight = CRUDLocalFlight()
