"""The airport reads beside the detail: `GET /api/airports/{iata}/hours`, the current line and its provenance.

A read-only companion to `GET /api/airports/{iata}` (routers/catalog.py), in its own file so the
airport work never edits the catalogue's router. Classified with the storefront reads
(services/access.py PUBLIC_WHEN_OPEN): public once the site is, any signed-in account until then,
and a hidden airport is a 404 here as it is on its page.
"""

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

from app.db import get_db
from app.models.hubs import AirportCategoryDetail, AirportHoursOut
from app.services import catalog_queries
from app.services.hours import store
from app.services.urls import category_from_slug

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


@router.get("/{iata}/hours", response_model=AirportHoursOut)
def airport_hours(iata: str, db: Session = Depends(get_db)) -> AirportHoursOut:
    """Collected or hand-entered, the date, and who or where from; kind "none" where neither exists."""
    iata = iata.upper()
    if len(iata) != 3 or not iata.isalpha() or not catalog_queries.airport_shops(db, iata):
        raise HTTPException(status_code=404, detail={"error_code": "AIRPORT_NOT_FOUND"})
    return catalog_queries.airport_hours_out(db, iata) or AirportHoursOut(kind="none")


@router.get("/{iata}/categories/{category_slug}", response_model=AirportCategoryDetail)
def airport_category(
    iata: str,
    category_slug: str,
    multi_only: bool = False,
    awarded_only: bool = False,
    exclusives_only: bool = False,
    sort: str = Query(default="featured", pattern="^(featured|compared|price|name)$"),
    limit: int = Query(default=24, ge=1, le=100),
    offset: int = Query(default=0, ge=0),
    db: Session = Depends(get_db),
) -> AirportCategoryDetail:
    """The category-at-airport page's data: the same object the server renders it from. A pair
    under the coverage bar, an unknown category word or a hidden airport is a 404."""
    category = category_from_slug(category_slug)
    if len(iata) != 3 or not iata.isalpha() or category is None:
        raise HTTPException(status_code=404, detail={"error_code": "AIRPORT_CATEGORY_NOT_FOUND"})
    detail = catalog_queries.airport_category_detail(
        db, iata.upper(), category, multi_only=multi_only, awarded_only=awarded_only,
        exclusives_only=exclusives_only, sort=sort, limit=limit, offset=offset,
    )
    if detail is None:
        raise HTTPException(status_code=404, detail={"error_code": "AIRPORT_CATEGORY_NOT_FOUND"})
    return detail
