"""Calibration statistics (descriptive — see app/calibration.py)."""

from __future__ import annotations

from fastapi import APIRouter, Depends, HTTPException
from psycopg import Connection

from ..audit import audit
from ..auth import User, current_user, require_center
from ..calibration import agreement, empirical_table, problem_usage
from ..configs import active_config, config_by_id
from ..db import fetchone, get_conn

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


def _config(conn: Connection, center_id: int, config_id: int | None) -> dict:
    if config_id is None:
        return active_config(conn, center_id)["config"]
    row = config_by_id(conn, config_id)
    if row["center_id"] != center_id:
        raise HTTPException(422, "Config belongs to another center")
    return row["config"]


def _source(source: str) -> str:
    if source not in ("imported", "tool"):
        raise HTTPException(422, "source must be 'imported' or 'tool'")
    return source


@router.get("/overview")
def overview(center_id: int, conn: Connection = Depends(get_conn), user: User = Depends(current_user)):
    require_center(user, center_id)
    counts = fetchone(
        conn,
        """SELECT (SELECT count(*)::int FROM forecasts WHERE center_id = %(c)s) AS forecasts,
                  (SELECT count(*)::int FROM forecasts WHERE center_id = %(c)s AND guidance_era = 'legacy') AS legacy_forecasts,
                  (SELECT min(valid_date) FROM forecasts WHERE center_id = %(c)s) AS first_forecast,
                  (SELECT max(valid_date) FROM forecasts WHERE center_id = %(c)s) AS last_forecast,
                  (SELECT count(*)::int FROM tool_runs WHERE center_id = %(c)s AND status = 'finalized') AS finalized_runs,
                  (SELECT count(*)::int FROM tool_runs WHERE center_id = %(c)s AND status = 'draft') AS draft_runs""",
        {"c": center_id},
    )
    return {**counts, "problem_usage": problem_usage(conn, center_id)}


@router.get("/guidance-audit")
def guidance_audit(center_id: int, era: str | None = None, conn: Connection = Depends(get_conn), user: User = Depends(current_user)):
    """How often past forecasts diverge from the current Forecast Guidance."""
    require_center(user, center_id)
    return audit(conn, center_id, era)


@router.get("/agreement")
def get_agreement(center_id: int, source: str = "imported", season: str | None = None, era: str | None = None,
                  config_id: int | None = None, conn: Connection = Depends(get_conn), user: User = Depends(current_user)):
    require_center(user, center_id)
    return agreement(conn, center_id, _config(conn, center_id, config_id), _source(source), season, era)


@router.get("/empirical-table")
def get_empirical_table(center_id: int, source: str = "imported", season: str | None = None, mode: str = "single",
                        era: str | None = None, config_id: int | None = None,
                        conn: Connection = Depends(get_conn), user: User = Depends(current_user)):
    require_center(user, center_id)
    if mode not in ("single", "dominant"):
        raise HTTPException(422, "mode must be 'single' or 'dominant'")
    return empirical_table(conn, center_id, _config(conn, center_id, config_id), _source(source), season, mode, era)
