"""
train_model.py

Trains the model the article is built around: a LightGBM 3-class
classifier (Sell / Hold / Buy) behind a scikit-learn Pipeline whose first
stage is a custom, window-dependent transformer. Every feature is computed
from a trailing window of raw bars (rolling z-score, ATR normalization,
rolling percentile rank), so the pipeline needs the recent history as
input, not a single row. skl2onnx has no converter for a custom transformer
like this one - exporting it means registering a converter and re-writing
the math with ONNX operators. Keeping the pipeline live in Python avoids
that work; the price, measured in the article, is a network hop per
decision instead of an in-process OnnxRun() call.

Run this once, offline, on exported historical bars. It trains on the
earliest TRAIN_FRACTION of the file and keeps the rest untouched for
backtest_offline.py. It writes model_pipeline.joblib, which
inference_service.py loads at startup.
"""

import numpy as np
import pandas as pd
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.pipeline import Pipeline
from lightgbm import LGBMClassifier
import joblib

# --- feature lookback windows, must match RollingFeatureTransformer below and
# --- the InpLookback the MQL5 EA sends per call
L1_RETURN_ZSCORE = 20   # window for the rolling log-return z-score
ATR_PERIOD = 14         # window for the ATR-normalized momentum term
L2_VOL_REGIME = 50      # window for the realized-volatility percentile rank

# --- training setup: demonstration defaults, not tuned values
FORWARD_BARS = 5          # label horizon, in bars
LABEL_THRESHOLD = 0.0006  # forward return needed for a Buy/Sell label (0.06%)
TRAIN_FRACTION = 0.70     # earliest share of the history used for training


class RollingFeatureTransformer(BaseEstimator, TransformerMixin):
    """
    The window-dependent piece. Given a 2D array of raw (close, volume)
    rows - oldest to newest - it computes the three engineered features
    the model is trained on. Only the close column feeds them; volume rides
    along in the contract so a future feature can use it:

      r_t          = rolling z-score of log returns over L1_RETURN_ZSCORE
      m_t          = ATR-normalized momentum over ATR_PERIOD
      vol_regime_t = percentile rank of rolling realized volatility over
                     L2_VOL_REGIME, bucketed 0 (low) / 1 (mid) / 2 (high)

    This exact class is imported by both train_model.py and
    inference_service.py, so there is only ever one implementation of the
    math - the model never sees a feature computed a different way at
    inference time than it saw at training time.
    """

    def fit(self, X, y=None):
        return self

    def transform(self, X):
        closes = X[:, 0]

        log_ret = np.diff(np.log(closes), prepend=np.log(closes[0]))
        r_t = _rolling_zscore(log_ret, L1_RETURN_ZSCORE)

        atr = _true_range_average(closes, ATR_PERIOD)
        momentum = closes - np.roll(closes, ATR_PERIOD)
        momentum[:ATR_PERIOD] = 0.0
        m_t = np.divide(momentum, atr, out=np.zeros_like(momentum), where=atr > 0)

        realized_vol = pd.Series(log_ret).rolling(L2_VOL_REGIME, min_periods=1).std().to_numpy()
        pct_rank = pd.Series(realized_vol).rolling(L2_VOL_REGIME, min_periods=1).apply(
            lambda w: (w.rank(pct=True).iloc[-1]), raw=False
        ).to_numpy()
        vol_regime_t = np.digitize(pct_rank, bins=[0.33, 0.66]).astype(float)

        # One feature row per input bar. Training needs the full history
        # aligned against every label; a live call only wants the newest
        # row, so that "latest only" slicing happens at prediction time in
        # inference_service.py instead - not here, where it would silently
        # collapse the whole training set down to a single row.
        return np.column_stack([r_t, m_t, vol_regime_t])


def _rolling_zscore(series: np.ndarray, window: int) -> np.ndarray:
    s = pd.Series(series)
    mean = s.rolling(window, min_periods=1).mean()
    std = s.rolling(window, min_periods=1).std().replace(0, np.nan)
    return ((s - mean) / std).fillna(0.0).to_numpy()


def _true_range_average(closes: np.ndarray, period: int) -> np.ndarray:
    tr = np.abs(np.diff(closes, prepend=closes[0]))
    return pd.Series(tr).rolling(period, min_periods=1).mean().to_numpy()


def build_pipeline() -> Pipeline:
    return Pipeline(steps=[
        ("features", RollingFeatureTransformer()),
        ("model", LGBMClassifier(
            objective="multiclass",
            num_class=3,
            n_estimators=300,
            learning_rate=0.03,
            max_depth=4,
            subsample=0.8,
            colsample_bytree=0.8,
            random_state=42,
        )),
    ])


def make_labels(closes: np.ndarray, forward_bars: int = FORWARD_BARS,
                threshold: float = LABEL_THRESHOLD) -> np.ndarray:
    """Sell=0 / Hold=1 / Buy=2, from a simple forward-return threshold. This
    is a demo model for the plumbing, not a claimed trading edge, so the
    labeling scheme is deliberately plain.

    A bar can only be labeled if the full forward window exists. The last
    forward_bars bars have no future to look at, so they get no label and the
    result is forward_bars shorter than closes. Callers must cut the feature
    rows to the same length."""
    fwd_ret = (closes[forward_bars:] - closes[:-forward_bars]) / closes[:-forward_bars]
    labels = np.ones(len(fwd_ret), dtype=int)
    labels[fwd_ret > threshold] = 2
    labels[fwd_ret < -threshold] = 0
    return labels


if __name__ == "__main__":
    # MT5's "Export Bars" writes a TAB-separated file with bracketed headers
    # (<DATE> <TIME> <OPEN> <HIGH> <LOW> <CLOSE> <TICKVOL> <VOL> <SPREAD>),
    # not a comma CSV with plain names - read it exactly as MT5 wrote it.
    df = pd.read_csv("gbpusd_m15_history.csv", sep="\t")
    df.columns = df.columns.str.strip()
    closes = df["<CLOSE>"].to_numpy()
    # Retail FX has no real traded volume, so <VOL> is just zeros here -
    # <TICKVOL> (price-update count per bar) is the standard proxy and the
    # only one of the two that actually carries information.
    volumes = df["<TICKVOL>"].to_numpy()

    # Chronological split: the model only ever sees the earliest part of the
    # file. The rest is kept back for backtest_offline.py.
    n_train = int(len(closes) * TRAIN_FRACTION)
    labels = make_labels(closes[:n_train])
    X_raw = np.column_stack([closes[:n_train], volumes[:n_train]])[:len(labels)]

    pipeline = build_pipeline()
    pipeline.fit(X_raw, labels)

    print(f"Training rows: {len(labels)} of {len(closes)} bars "
          f"({df['<DATE>'].iloc[0]} to {df['<DATE>'].iloc[len(labels) - 1]})")
    print("Class balance (Sell/Hold/Buy):", np.bincount(labels, minlength=3))
    joblib.dump(pipeline, "model_pipeline.joblib")
    print("Saved model_pipeline.joblib")
