"""Isotonic probability calibration trainer from resolved prediction history."""

import time
from pathlib import Path

import joblib
import numpy as np
from sklearn.isotonic import IsotonicRegression

from .data_loader import load_meta_prediction_frame


class IsotonicTrainer:
    model_name = "meta_isotonic"
    artifact_path = Path("models") / "meta_isotonic.joblib"

    def run(self, days: int = 180) -> dict:
        start = time.time()
        frame = load_meta_prediction_frame(days)
        if frame.empty or len(frame) < 50:
            return {
                "model": self.model_name,
                "status": "skipped",
                "metrics": {"samples": len(frame)},
                "duration_seconds": round(time.time() - start, 2),
                "artifact_path": "",
                "error": "Need at least 50 resolved predictions",
            }

        predicted = frame["probability"].astype(float).to_numpy()
        actual = frame["was_correct"].astype(float).to_numpy()

        model = IsotonicRegression(y_min=0.05, y_max=0.95, out_of_bounds="clip")
        model.fit(predicted, actual)
        calibrated = model.predict(predicted)
        mae = float(np.mean(np.abs(calibrated - actual)))

        self.artifact_path.parent.mkdir(parents=True, exist_ok=True)
        joblib.dump(
            {
                "model": model,
                "trained_at": str(int(time.time())),
                "accuracy": 1.0 - mae,
                "samples": len(predicted),
            },
            self.artifact_path,
        )

        return {
            "model": self.model_name,
            "status": "success",
            "metrics": {
                "mae": mae,
                "samples": len(predicted),
            },
            "duration_seconds": round(time.time() - start, 2),
            "artifact_path": str(self.artifact_path),
        }
