"""Meta-confidence model for champion/challenger promotion and filtering."""

import os
from pathlib import Path

import joblib
import numpy as np
import pandas as pd

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


class StackingMetaModel:
    def __init__(self) -> None:
        self.version = "0.1.0"
        self.is_loaded = False
        self.last_trained: str | None = None
        self.accuracy: float | None = None
        self.model = None
        self.columns: list[str] = []

    def load(self) -> None:
        path = MODEL_DIR / "meta_stacking.joblib"
        try:
            data = joblib.load(path)
            self.model = data["model"]
            self.columns = data.get("columns", [])
            self.last_trained = data.get("trained_at")
            self.accuracy = data.get("accuracy")
            self.is_loaded = True
        except Exception:
            self.model = None
            self.columns = []
            self.is_loaded = True

    def predict(self, features: dict) -> dict:
        if self.model is None:
            probability = float(features.get("probability", 0.5))
            return {
                "correctness_probability": round(probability, 4),
                "verdict": "take" if probability >= 0.6 else "skip",
                "model": "heuristic-meta-stacking",
            }

        frame = pd.DataFrame([features])
        frame = pd.get_dummies(frame, columns=["model", "horizon"], dtype=float)
        for column in self.columns:
            if column not in frame:
                frame[column] = 0.0
        frame = frame[self.columns]
        probability = float(self.model.predict_proba(frame)[0][1])
        return {
            "correctness_probability": round(probability, 4),
            "verdict": "take" if probability >= 0.6 else "skip",
            "model": "meta_stacking",
        }
