from pydantic import BaseModel, validator
from datetime import datetime
from typing import Optional
from enum import Enum


class LocalFlightType(str, Enum):
    LOCAL = "LOCAL"
    CIRCUITS = "CIRCUITS"
    DEPARTURE = "DEPARTURE"


class LocalFlightStatus(str, Enum):
    BOOKED_OUT = "BOOKED_OUT"
    DEPARTED = "DEPARTED"
    LANDED = "LANDED"
    CANCELLED = "CANCELLED"


class SubmissionSource(str, Enum):
    ADMIN = "ADMIN"
    PUBLIC = "PUBLIC"


class LocalFlightBase(BaseModel):
    registration: str
    type: Optional[str] = None  # Aircraft type - optional, can be looked up later
    callsign: Optional[str] = None
    pob: int
    flight_type: LocalFlightType
    duration: Optional[int] = 45  # Duration in minutes, default 45
    etd: Optional[datetime] = None  # Estimated Time of Departure
    notes: Optional[str] = None

    @validator('registration')
    def validate_registration(cls, v):
        if not v or len(v.strip()) == 0:
            raise ValueError('Aircraft registration is required')
        return v.strip().upper()

    @validator('type', pre=True, always=False)
    def validate_type(cls, v):
        if v is None or (isinstance(v, str) and len(v.strip()) == 0):
            return None
        if isinstance(v, str):
            return v.strip()
        return v

    @validator('pob')
    def validate_pob(cls, v):
        if v is not None and v < 1:
            raise ValueError('Persons on board must be at least 1')
        return v


class LocalFlightCreate(LocalFlightBase):
    pass


class LocalFlightUpdate(BaseModel):
    registration: Optional[str] = None
    type: Optional[str] = None
    callsign: Optional[str] = None
    pob: Optional[int] = None
    flight_type: Optional[LocalFlightType] = None
    duration: Optional[int] = None
    status: Optional[LocalFlightStatus] = None
    etd: Optional[datetime] = None
    departed_dt: Optional[datetime] = None
    circuits: Optional[int] = None
    notes: Optional[str] = None


class LocalFlightStatusUpdate(BaseModel):
    status: LocalFlightStatus
    timestamp: Optional[datetime] = None


class LocalFlightInDBBase(LocalFlightBase):
    id: int
    status: LocalFlightStatus
    created_dt: datetime
    etd: Optional[datetime] = None
    departed_dt: Optional[datetime] = None
    landed_dt: Optional[datetime] = None
    circuits: Optional[int] = None
    created_by: Optional[str] = None
    updated_at: datetime
    submitted_via: Optional[SubmissionSource] = None
    pilot_email: Optional[str] = None

    class Config:
        from_attributes = True


class LocalFlight(LocalFlightInDBBase):
    pass