"""Simple PSI/z-score drift monitor for live feature health."""

import os
from pathlib import Path

import joblib

MODEL_DIR = Path(os.getenv("MODEL_DIR", "models"))


class DriftMonitor:
    def __init__(self) -> None:
        self.version = "0.1.0"
        self.is_loaded = False
        self.last_trained: str | None = None
        self.baseline: dict[str, dict[str, float]] = {}

    def load(self) -> None:
        path = MODEL_DIR / "meta_drift_detector.joblib"
        try:
            data = joblib.load(path)
            self.baseline = data.get("baseline", {})
            self.last_trained = data.get("trained_at")
            self.is_loaded = True
        except Exception:
            self.baseline = {}
            self.is_loaded = True

    def check(self, features: dict) -> dict:
        if not self.baseline:
            return {"drift_score": 0.0, "status": "unknown", "alerts": [], "model": "identity-drift"}

        alerts: list[str] = []
        scores: list[float] = []
        for name, stats in self.baseline.items():
            value = float(features.get(name, stats.get("mean", 0.0)))
            mean = float(stats.get("mean", 0.0))
            std = max(float(stats.get("std", 0.0)), 1e-6)
            z_score = abs(value - mean) / std
            scores.append(min(1.0, z_score / 4.0))
            if z_score >= 3:
                alerts.append(f"{name}_z{z_score:.2f}")

        drift_score = round(sum(scores) / len(scores), 4) if scores else 0.0
        status = "high" if drift_score >= 0.6 else "moderate" if drift_score >= 0.3 else "stable"
        return {
            "drift_score": drift_score,
            "status": status,
            "alerts": alerts[:5],
            "model": "meta_drift_detector",
        }
