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.overflight import Overflight, OverflightStatus
from app.schemas.overflight import OverflightCreate, OverflightUpdate, OverflightStatusUpdate
from app.models.journal import EntityType
from app.crud.crud_journal import journal


class CRUDOverflight:
    def get(self, db: Session, overflight_id: int) -> Optional[Overflight]:
        return db.query(Overflight).filter(Overflight.id == overflight_id).first()

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

    def get_active_overflights(self, db: Session) -> List[Overflight]:
        """Get currently active overflights"""
        return db.query(Overflight).filter(
            Overflight.status == OverflightStatus.ACTIVE
        ).order_by(desc(Overflight.created_dt)).all()

    def get_overflights_today(self, db: Session) -> List[Overflight]:
        """Get today's overflights"""
        today = date.today()
        return db.query(Overflight).filter(
            func.date(Overflight.created_dt) == today
        ).order_by(Overflight.created_dt).all()

    def create(self, db: Session, obj_in: OverflightCreate, created_by: str) -> Overflight:
        db_obj = Overflight(
            **obj_in.dict(),
            created_by=created_by,
            status=OverflightStatus.ACTIVE
        )
        db.add(db_obj)
        db.commit()
        db.refresh(db_obj)
        
        # Log creation in journal
        journal.log_change(
            db,
            EntityType.OVERFLIGHT,
            db_obj.id,
            f"Overflight created: {obj_in.registration} from {obj_in.departure_airfield} to {obj_in.destination_airfield}",
            created_by,
            None
        )
        
        return db_obj

    def update(self, db: Session, db_obj: Overflight, obj_in: OverflightUpdate, user: str = "system", user_ip: Optional[str] = None) -> Overflight:
        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):
                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
            
            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.OVERFLIGHT,
                    db_obj.id,
                    change,
                    user,
                    user_ip
                )
        
        return db_obj

    def update_status(
        self, 
        db: Session, 
        overflight_id: int, 
        status: OverflightStatus,
        timestamp: Optional[datetime] = None,
        user: str = "system",
        user_ip: Optional[str] = None
    ) -> Optional[Overflight]:
        db_obj = self.get(db, overflight_id)
        if not db_obj:
            return None
        
        # Ensure status is an OverflightStatus enum
        if isinstance(status, str):
            status = OverflightStatus(status)
        
        old_status = db_obj.status
        db_obj.status = status
        
        # Set timestamp if transitioning to INACTIVE (QSY'd)
        current_time = timestamp if timestamp is not None else datetime.utcnow()
        if status == OverflightStatus.INACTIVE:
            db_obj.qsy_dt = current_time
        
        db.add(db_obj)
        db.commit()
        db.refresh(db_obj)
        
        # Log status change in journal
        journal.log_change(
            db,
            EntityType.OVERFLIGHT,
            overflight_id,
            f"Status changed from {old_status.value} to {status.value}",
            user,
            user_ip
        )
        
        return db_obj

    def cancel(self, db: Session, overflight_id: int, user: str = "system", user_ip: Optional[str] = None) -> Optional[Overflight]:
        db_obj = self.get(db, overflight_id)
        if db_obj:
            old_status = db_obj.status
            db_obj.status = OverflightStatus.CANCELLED
            db.add(db_obj)
            db.commit()
            db.refresh(db_obj)
            
            # Log cancellation in journal
            journal.log_change(
                db,
                EntityType.OVERFLIGHT,
                overflight_id,
                f"Status changed from {old_status.value} to CANCELLED",
                user,
                user_ip
            )
        return db_obj


overflight = CRUDOverflight()
