from fastapi import APIRouter, Depends, File, Form, HTTPException, Query, UploadFile

from app.errors import RoutingError
from app.auth import require_user
from app.store import User, SessionOwnershipError
from app.dependencies import (
    resolve_route,
    build_orchestrator,
    resolve_input_endpoint,
    get_store,
)
from app.quota import enforce_quota, record_usage, QuotaExceededError

router = APIRouter()


@router.post("/transcribe")
async def transcribe(
    file: UploadFile = File(...),
    language: str | None = Form(default=None),
    input_endpoint: str | None = Form(default=None),
    stt_provider: str | None = Form(default=None),
    session_id: str | None = Query(
        default=None,
        description="Optional session id to apply a stored route",
    ),
    user: User = Depends(require_user),
):
    overrides = {
        "input_endpoint": input_endpoint,
        "language": language,
        "stt_provider": stt_provider,
    }

    try:
        route = resolve_route(user, session_id, overrides)
        orchestrator = build_orchestrator(route)
        source = await resolve_input_endpoint(route)
    except SessionOwnershipError as exc:
        raise HTTPException(status_code=403, detail=str(exc))
    except RoutingError as exc:
        raise HTTPException(status_code=422, detail=str(exc))

    store = get_store()
    try:
        enforce_quota(user, store)
    except QuotaExceededError as exc:
        raise HTTPException(status_code=429, detail=str(exc))

    content = await file.read()
    suffix = (file.filename or "audio.wav").rsplit(".", 1)[-1].lower()

    try:
        trace = await orchestrator.transcribe_only(
            content,
            fmt=suffix,
            language=route.language,
            input=source,
        )
    except Exception as exc:
        raise HTTPException(status_code=502, detail=str(exc))

    record_usage(user, store, len(trace.raw_transcript or ""))

    return {"route": route.as_dict(), "trace": trace.model_dump()}
