"""Short-horizon microstructure specialist trainer."""

import time
from pathlib import Path

import joblib
import numpy as np
from sklearn.metrics import accuracy_score, f1_score

from .data_loader import load_microstructure_training_frame


class MicrostructureTrainer:
    model_name = "microstructure_specialist"
    artifact_path = Path("models") / "microstructure_specialist.joblib"
    feature_keys = [
        "return_1",
        "volume_ratio",
        "range_pct",
        "wick_imbalance",
        "trade_intensity",
        "price_vs_sma20",
        "volatility_5",
    ]

    def run(self, days: int = 30) -> dict:
        start = time.time()
        frame = load_microstructure_training_frame(days=days, timeframe="1m")
        if frame.empty or len(frame) < 80:
            return {
                "model": self.model_name,
                "status": "skipped",
                "metrics": {"samples": len(frame)},
                "duration_seconds": round(time.time() - start, 2),
                "artifact_path": "",
                "error": "Need at least 80 microstructure samples",
            }

        X = frame[self.feature_keys].fillna(0.0).astype(np.float32).values
        y = frame["y"].astype(np.int64).values
        n = len(X)
        split = int(n * 0.80)
        X_train, X_test = X[:split], X[split:]
        y_train, y_test = y[:split], y[split:]

        try:
            import xgboost as xgb

            model = xgb.XGBClassifier(
                n_estimators=220,
                max_depth=4,
                learning_rate=0.05,
                subsample=0.85,
                colsample_bytree=0.85,
                objective="multi:softprob",
                num_class=3,
                eval_metric="mlogloss",
                random_state=42,
            )
            model.fit(X_train, y_train)
            engine = "xgboost"
        except Exception:
            from sklearn.ensemble import RandomForestClassifier

            model = RandomForestClassifier(
                n_estimators=250,
                max_depth=10,
                min_samples_leaf=4,
                class_weight="balanced_subsample",
                random_state=42,
                n_jobs=-1,
            )
            model.fit(X_train, y_train)
            engine = "random_forest"

        preds = model.predict(X_test)
        accuracy = float(accuracy_score(y_test, preds))
        f1 = float(f1_score(y_test, preds, average="weighted", zero_division=0))

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

        return {
            "model": self.model_name,
            "status": "success",
            "metrics": {
                "accuracy": accuracy,
                "f1": f1,
                "test_samples": len(X_test),
            },
            "duration_seconds": round(time.time() - start, 2),
            "artifact_path": str(self.artifact_path),
        }
