from pathlib import Path
from typing import Optional

import pandas as pd
from fastapi import APIRouter, Depends, HTTPException, Query

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

router = APIRouter(prefix="/dataset", tags=["Dataset de Estudiantes"])
settings = get_settings()

DATASETS_DIR = Path(settings.models_base_path) / "datasets"
CLEAN_CSV = DATASETS_DIR / "clean_dataset.csv"


def _load_clean() -> pd.DataFrame:
    return pd.read_csv(CLEAN_CSV)


@router.get("/summary", summary="Resumen estadístico del dataset")
def get_summary(_: UsuarioAdmin = Depends(get_current_admin)):
    df = _load_clean()
    return {
        "total_students": len(df),
        "countries": df["country"].value_counts().to_dict(),
        "courses": df["course"].value_counts().to_dict(),
        "gender_distribution": df["gender"].value_counts().to_dict(),
        "support_level_distribution": df["support_level"].value_counts().to_dict(),
        "grade_tendency_distribution": df["grade_tendency"].value_counts().to_dict(),
        "avg_final": {
            "mean": round(df["avg_final"].mean(), 3),
            "std": round(df["avg_final"].std(), 3),
            "min": round(df["avg_final"].min(), 3),
            "max": round(df["avg_final"].max(), 3),
        },
        "attendance_absences": {
            "mean": round(df["attendance_absences_total"].mean(), 2),
            "max": int(df["attendance_absences_total"].max()),
        },
        "pass_rate_mean": round(df["passed_rate_percent"].mean(), 2),
    }


@router.get("/students", summary="Lista de estudiantes con filtros opcionales")
def get_students(
    page: int = Query(1, ge=1),
    page_size: int = Query(50, ge=1, le=500),
    country: Optional[str] = Query(None),
    course: Optional[str] = Query(None),
    gender: Optional[str] = Query(None),
    support_level: Optional[str] = Query(None),
    grade_tendency: Optional[str] = Query(None),
    _: UsuarioAdmin = Depends(get_current_admin),
):
    df = _load_clean()

    if country:
        df = df[df["country"].str.lower() == country.lower()]
    if course:
        df = df[df["course"].str.lower() == course.lower()]
    if gender:
        df = df[df["gender"].str.upper() == gender.upper()]
    if support_level:
        df = df[df["support_level"].str.lower() == support_level.lower()]
    if grade_tendency:
        df = df[df["grade_tendency"].str.lower() == grade_tendency.lower()]

    total = len(df)
    start = (page - 1) * page_size
    page_df = df.iloc[start : start + page_size]

    return {
        "total": total,
        "page": page,
        "page_size": page_size,
        "items": page_df.fillna("").to_dict(orient="records"),
    }


@router.get("/students/{student_id}", summary="Datos completos de un estudiante")
def get_student(student_id: str, _: UsuarioAdmin = Depends(get_current_admin)):
    df = _load_clean()
    row = df[df["student_id"] == student_id]
    if row.empty:
        raise HTTPException(status_code=404, detail=f"Estudiante '{student_id}' no encontrado")
    return row.fillna("").to_dict(orient="records")[0]


@router.get("/fields", summary="Lista de columnas del dataset")
def get_fields(_: UsuarioAdmin = Depends(get_current_admin)):
    df = _load_clean()
    return {"fields": list(df.columns)}
