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

from core.database import get_db
from ..models import Route
from ..schemas.route import RouteResponse, RouteListResponse

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


@router.get("/", response_model=RouteListResponse)
def get_routes(
    origin: Optional[str] = Query(default=None),
    dest: Optional[str] = Query(default=None),
    delay_risk: Optional[str] = Query(default=None),
    min_flights: int = Query(default=100, ge=0),
    sort_by: str = Query(default="flight_count"),
    limit: int = Query(default=200, le=1000),
    db: Session = Depends(get_db),
):
    query = db.query(Route).filter(Route.flight_count >= min_flights)

    if origin:
        query = query.filter(Route.origin == origin.upper())
    if dest:
        query = query.filter(Route.dest == dest.upper())
    if delay_risk:
        levels = [r.strip() for r in delay_risk.split(",")]
        query = query.filter(Route.delay_risk.in_(levels))

    sort_col = getattr(Route, sort_by, Route.flight_count)
    routes = query.order_by(sort_col.desc()).limit(limit).all()
    return RouteListResponse(routes=routes, count=len(routes))
