"""Baseline feature-distribution trainer for drift monitoring."""

import time
from pathlib import Path

import joblib

from .data_loader import load_meta_prediction_frame


class DriftMonitorTrainer:
    model_name = "meta_drift_detector"
    artifact_path = Path("models") / "meta_drift_detector.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",
            }

        numeric = frame.drop(columns=["model", "horizon", "was_correct"]).fillna(0.0)
        baseline = {
            column: {
                "mean": float(numeric[column].mean()),
                "std": float(max(numeric[column].std(), 1e-6)),
                "p10": float(numeric[column].quantile(0.10)),
                "p90": float(numeric[column].quantile(0.90)),
            }
            for column in numeric.columns
        }

        self.artifact_path.parent.mkdir(parents=True, exist_ok=True)
        joblib.dump(
            {
                "baseline": baseline,
                "trained_at": str(int(time.time())),
            },
            self.artifact_path,
        )

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