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


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) -> LocalFlight:
        update_data = obj_in.dict(exclude_unset=True)
        
        for field, value in update_data.items():
            if value is not None:
                setattr(db_obj, field, value)
        
        db.add(db_obj)
        db.commit()
        db.refresh(db_obj)
        return db_obj

    def update_status(
        self, 
        db: Session, 
        flight_id: int, 
        status: LocalFlightStatus,
        timestamp: Optional[datetime] = 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)
        
        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
        
        db.add(db_obj)
        db.commit()
        db.refresh(db_obj)
        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()
