"""Catalyst and event-aware medium-horizon classifier."""

import os
from pathlib import Path

import joblib
import numpy as np

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


class CatalystEventModel:
    FEATURE_KEYS = [
        "days_to_event",
        "event_risk",
        "within_24h",
        "within_72h",
        "within_7d",
        "is_fomc",
        "is_cpi",
        "is_nfp",
        "returns_1d",
        "returns_7d",
        "volatility_14d",
        "fear_greed",
        "funding_rate",
    ]

    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

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

    def predict(self, features: dict) -> dict:
        if self.model is None:
            event_risk = float(features.get("event_risk", 0.0))
            ret = float(features.get("returns_1d", 0.0))
            direction = "up" if ret > 1 else "down" if ret < -1 else "sideways"
            probability = max(0.4, min(0.75, 0.55 + event_risk * 0.15))
            return {
                "direction": direction,
                "probability": round(probability, 4),
                "event_risk": round(event_risk, 4),
                "model": "heuristic-catalyst-event",
            }

        x = np.array([[features.get(k, 0.0) for k in self.FEATURE_KEYS]], dtype=np.float32)
        proba = self.model.predict_proba(x)[0]
        idx = int(np.argmax(proba))
        direction = {0: "down", 1: "sideways", 2: "up"}.get(idx, "sideways")
        return {
            "direction": direction,
            "probability": round(float(proba[idx]), 4),
            "event_risk": round(float(features.get("event_risk", 0.0)), 4),
            "model": "catalyst_event",
        }
