import json
from pathlib import Path

from fastapi import APIRouter, Depends, HTTPException
from fastapi.responses import HTMLResponse

from ..core.config import get_settings
from ..db_models.internal import UsuarioAdmin
from ..dependencies import get_current_admin

router = APIRouter(prefix="/statistics", tags=["Estadísticas"])
settings = get_settings()

STATS_DIR = Path(settings.models_base_path) / "statistics"
FIGURES_DIR = STATS_DIR / "iframe_figures"

DASHBOARDS: dict[str, str] = {
    "attendance": "dashboard_attendance.json",
    "demographics": "dashboard_demographics.json",
    "school_group": "dashboard_school_group.json",
    "student_performance": "dashboard_student_performance.json",
    "subject_performance": "dashboard_subject_performance.json",
    "support": "dashboard_support.json",
    "term_progression": "dashboard_term_progression.json",
}


@router.get("/", summary="Lista de dashboards y figuras disponibles")
def list_statistics(_: UsuarioAdmin = Depends(get_current_admin)):
    figures = sorted(f.stem for f in FIGURES_DIR.glob("*.html")) if FIGURES_DIR.exists() else []
    return {
        "dashboards": list(DASHBOARDS.keys()),
        "iframe_figures": figures,
    }


@router.get("/{name}", summary="Datos Plotly JSON de un dashboard estadístico")
def get_dashboard(name: str, _: UsuarioAdmin = Depends(get_current_admin)):
    if name not in DASHBOARDS:
        raise HTTPException(
            status_code=404,
            detail=f"Dashboard '{name}' no encontrado. Disponibles: {list(DASHBOARDS.keys())}",
        )
    path = STATS_DIR / DASHBOARDS[name]
    return json.loads(path.read_text(encoding="utf-8"))


@router.get("/figures/{name}", response_class=HTMLResponse, summary="Figura interactiva HTML (iframe)")
def get_figure(name: str, _: UsuarioAdmin = Depends(get_current_admin)):
    path = FIGURES_DIR / f"{name}.html"
    if not path.exists():
        available = sorted(f.stem for f in FIGURES_DIR.glob("*.html"))
        raise HTTPException(
            status_code=404,
            detail=f"Figura '{name}' no encontrada. Disponibles: {available}",
        )
    return HTMLResponse(content=path.read_text(encoding="utf-8"))
