from __future__ import annotations

from pathlib import Path
from typing import List

import numpy as np
import pandas as pd


def _history_group(frame: pd.DataFrame) -> pd.Series:
    semesters = pd.to_numeric(frame.get("hist_semester_count", 0), errors="coerce").fillna(0)
    return pd.cut(
        semesters,
        bins=[-np.inf, 0, 1, 2, 5, np.inf],
        labels=["0 semesters", "1 semester", "2 semesters", "3-5 semesters", "6+ semesters"],
    ).astype(str)


def analyze_prediction_directory(
    experiment_dir: Path,
    warning_col: str,
) -> pd.DataFrame:
    files = sorted(Path(experiment_dir).glob("predictions_fold_*.csv"))
    if not files:
        raise FileNotFoundError(f"No prediction files in {experiment_dir}")
    frame = pd.concat([pd.read_csv(path, low_memory=False) for path in files], ignore_index=True)
    if warning_col not in frame.columns:
        raise ValueError(f"Missing warning column: {warning_col}")
    y = frame["true_failure"].astype(bool)
    warn = frame[warning_col].astype(bool)
    frame["confusion_group"] = np.select(
        [y & warn, y & ~warn, ~y & warn], ["TP", "FN", "FP"], default="TN"
    )
    frame["history_depth_group"] = _history_group(frame)
    if "hist_target_course_count" in frame.columns:
        frame["course_history_group"] = np.where(
            pd.to_numeric(frame["hist_target_course_count"], errors="coerce").fillna(0) > 0,
            "course history available",
            "no course history",
        )
    else:
        frame["course_history_group"] = "unknown"
    rows: List[dict] = []
    for dimension in ["fold", "grade_band", "history_depth_group", "course_history_group"]:
        for value, group in frame.groupby(dimension, dropna=False):
            for confusion, sub in group.groupby("confusion_group"):
                rows.append(
                    {
                        "dimension": dimension,
                        "group": value,
                        "confusion_group": confusion,
                        "rows": len(sub),
                        "mean_score": float(sub["classification_score"].mean()),
                        "mean_true_grade": float(sub["true_grade"].mean()),
                    }
                )
    return pd.DataFrame(rows)
