from fastapi import APIRouter, Depends, Query, HTTPException
from sqlalchemy.orm import Session
from typing import Optional

from core.database import get_db
from ..models import Airport, Route
from ..schemas.airport import AirportResponse, AirportListResponse

router = APIRouter(prefix="/api/airports", tags=["airports"])


@router.get("/", response_model=AirportListResponse)
def get_airports(
    state: Optional[str] = Query(default=None),
    min_flights: int = Query(default=0, ge=0),
    sort_by: str = Query(default="total_flights"),
    limit: int = Query(default=100, le=500),
    db: Session = Depends(get_db),
):
    query = db.query(Airport).filter(Airport.total_flights >= min_flights)
    if state:
        query = query.filter(Airport.state == state.upper())

    sort_col = getattr(Airport, sort_by, Airport.total_flights)
    airports = query.order_by(sort_col.desc()).limit(limit).all()
    return AirportListResponse(airports=airports, count=len(airports))


@router.get("/{iata}", response_model=AirportResponse)
def get_airport(iata: str, db: Session = Depends(get_db)):
    airport = db.query(Airport).filter(Airport.iata == iata.upper()).first()
    if not airport:
        raise HTTPException(status_code=404, detail=f"Airport {iata} not found")
    return airport


@router.get("/{iata}/diagnostics")
def get_diagnostics(iata: str, db: Session = Depends(get_db)):
    """Raw metrics + connected routes for the data explorer modal."""
    airport = db.query(Airport).filter(Airport.iata == iata.upper()).first()
    if not airport:
        raise HTTPException(status_code=404, detail=f"Airport {iata} not found")

    routes = (
        db.query(Route)
        .filter((Route.origin == iata.upper()) | (Route.dest == iata.upper()))
        .order_by(Route.flight_count.desc())
        .all()
    )

    _r = lambda x: round(x, 2) if x else 0

    return {
        "airport": {
            "iata": airport.iata,
            "name": airport.name,
            "city": airport.city,
            "state": airport.state,
            "lat": airport.lat,
            "lon": airport.lon,
            "total_flights": airport.total_flights or 0,
            "total_departures": airport.total_departures or 0,
            "total_arrivals": airport.total_arrivals or 0,
            "avg_arr_delay": _r(airport.avg_arr_delay),
            "avg_dep_delay": _r(airport.avg_dep_delay),
            "pct_delayed": _r(airport.pct_delayed),
            "delay_score": _r(airport.delay_score),
            "carrier_pct": _r(airport.carrier_pct),
            "weather_pct": _r(airport.weather_pct),
            "nas_pct": _r(airport.nas_pct),
            "late_aircraft_pct": _r(airport.late_aircraft_pct),
            "recovery_score": _r(airport.recovery_score),
            "propagation_legs": airport.propagation_legs or 0,
            "data_sources": [
                "BTS On-Time Performance (2023-2024)",
                "Carrier Reporting to DOT",
            ],
        },
        "routes": [
            {
                "origin": r.origin,
                "dest": r.dest,
                "flight_count": r.flight_count or 0,
                "avg_delay": _r(r.avg_delay),
                "median_delay": _r(r.median_delay),
                "std_delay": _r(r.std_delay),
                "pct_delayed": _r(r.pct_delayed),
                "avg_distance": _r(r.avg_distance),
                "delay_risk": r.delay_risk or "low",
            }
            for r in routes
        ],
        "meta": {
            "route_count": len(routes),
            "query_airport": iata.upper(),
        },
    }
