"""Distribution-free conformal interval calibrator for target forecasts."""

import os
from pathlib import Path

import joblib

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


class ConformalIntervalModel:
    def __init__(self) -> None:
        self.version = "0.1.0"
        self.is_loaded = False
        self.last_trained: str | None = None
        self.coverage: float | None = None
        self.lower_residual_pct = 0.0
        self.upper_residual_pct = 0.0

    def load(self) -> None:
        path = MODEL_DIR / "interval_conformal_calibrator.joblib"
        try:
            data = joblib.load(path)
            self.lower_residual_pct = float(data.get("lower_residual_pct", 0.0))
            self.upper_residual_pct = float(data.get("upper_residual_pct", 0.0))
            self.coverage = data.get("coverage")
            self.last_trained = data.get("trained_at")
            self.is_loaded = True
        except Exception:
            self.is_loaded = True

    def apply(self, low_change_pct: float, base_change_pct: float, high_change_pct: float) -> dict:
        if self.lower_residual_pct == 0.0 and self.upper_residual_pct == 0.0:
            return {
                "low_change_pct": low_change_pct,
                "base_change_pct": base_change_pct,
                "high_change_pct": high_change_pct,
                "coverage": self.coverage,
                "model": "identity-conformal",
            }

        adjusted_low = min(low_change_pct, base_change_pct + self.lower_residual_pct)
        adjusted_high = max(high_change_pct, base_change_pct + self.upper_residual_pct)
        return {
            "low_change_pct": round(adjusted_low, 4),
            "base_change_pct": round(base_change_pct, 4),
            "high_change_pct": round(adjusted_high, 4),
            "coverage": self.coverage,
            "model": "interval_conformal_calibrator",
        }
