"""
backtest_offline.py

A standalone, MT5-independent replay of the GrpcInference strategy.

Why this exists: MetaTrader 5's Strategy Tester runs its local agent in a
network-sandboxed process, and WebRequest() fails there even to 127.0.0.1
with the URL whitelisted (a real run of this EA logged "WebRequest failed,
code=-1" on all 17,358 bars). That is a limit of the tester for any
WebRequest-dependent EA, not a bug in the EA or the gateway. This script
replays the same historical bars directly against the trained pipeline,
skipping MT5 and the network hop, and simulates the EA's decision logic
(confidence gate, ATR-based stops, one position at a time).

Time model, per bar t (the EA works the same way on every new bar):
  1. The signal comes from bar t-1, which has just closed.
  2. At the open of bar t an opposite position is closed at open[t], and a
     new position is opened at open[t] with stops from the ATR of bar t-1.
  3. The high/low range of bar t is then tested against that position's
     stop and target. A position opened at the open of bar t is therefore
     tested on bar t itself. If one bar touches both levels, the stop is
     booked first.

The model is trained on the earliest TRAIN_FRACTION of the file. The same
bars are replayed twice: the training segment (in-sample) and the untouched
remainder (out-of-sample). No spread, commission, slippage or gaps are
modeled. The script checks the decision plumbing; it is not a performance
estimate.

Run this after train_model.py has produced model_pipeline.joblib:

    python backtest_offline.py
"""

import hashlib
import json

import numpy as np
import pandas as pd
import joblib

# train_model.py pickled the pipeline while running as __main__, so joblib.load()
# looks for RollingFeatureTransformer in this script's namespace. The import is
# never called directly; without it the load fails with AttributeError.
from train_model import RollingFeatureTransformer, TRAIN_FRACTION  # noqa: F401

# --- must mirror GrpcInference_EA.mq5's own input defaults ---
LOOKBACK = 64
ATR_PERIOD = 14
SL_ATR_MULT = 2.0
TP_ATR_MULT = 3.0
PIP = 0.0001  # GBPUSD, 5-digit broker

HISTORY_FILE = "gbpusd_m15_history.csv"
THRESHOLDS = [0.55, 0.50, 0.45, 0.40, 0.00]


#+-------------------------------------------------------------------+
#| wilder_atr                                                        |
#+-------------------------------------------------------------------+
def wilder_atr(high: np.ndarray, low: np.ndarray, close: np.ndarray, period: int) -> np.ndarray:
    """Wilder-smoothed ATR, used here as a stand-in for the terminal's iATR(),
    which GetStopDistance() in the EA calls. The two average the true range
    differently, so the stops in this replay are close to, but not identical
    to, the EA's. It is also a different ATR from the simpler one inside
    RollingFeatureTransformer, and the two are deliberately kept separate."""
    n = len(close)
    tr = np.zeros(n)
    tr[0] = high[0] - low[0]
    for i in range(1, n):
        tr[i] = max(high[i] - low[i], abs(high[i] - close[i - 1]), abs(low[i] - close[i - 1]))

    atr = np.full(n, np.nan)
    atr[period - 1] = tr[:period].mean()
    for i in range(period, n):
        atr[i] = (atr[i - 1] * (period - 1) + tr[i]) / period
    return atr


#+-------------------------------------------------------------------+
#| compute_probabilities                                             |
#+-------------------------------------------------------------------+
def compute_probabilities(pipeline, closes: np.ndarray, volumes: np.ndarray) -> np.ndarray:
    """P(sell), P(hold), P(buy) for the signal taken at the close of each bar.
    Row s holds the prediction made when bar s has just closed, from the same
    trailing LOOKBACK-bar window the EA sends. Rows without a full window stay
    NaN. The model sees each window exactly as it would live; only the
    LightGBM step is batched, which gives identical numbers and runs faster."""
    n = len(closes)
    probs = np.full((n, 3), np.nan)
    features = pipeline.named_steps["features"]
    rows = []
    for s in range(LOOKBACK - 1, n - 1):
        window = np.column_stack([closes[s - LOOKBACK + 1:s + 1], volumes[s - LOOKBACK + 1:s + 1]])
        rows.append(features.transform(window)[-1])
        if len(rows) % 5000 == 0:
            print(f"  features {len(rows)}/{n - LOOKBACK}", flush=True)
    probs[LOOKBACK - 1:n - 1] = pipeline.named_steps["model"].predict_proba(np.array(rows))
    # gateway.py rounds p_sell/p_hold/p_buy to 4 decimals before the EA ever sees them
    # (round(response.p_sell, 4), etc.), so round here too: DecideSignal() in the EA
    # always acts on the rounded value, never the raw model output.
    return np.round(probs, 4)


#+-------------------------------------------------------------------+
#| signals_for                                                       |
#+-------------------------------------------------------------------+
def signals_for(probs: np.ndarray, threshold: float) -> np.ndarray:
    """The EA's DecideSignal(): +1 Buy, -1 Sell, 0 Hold. NaN rows give 0."""
    p_sell, p_buy = probs[:, 0], probs[:, 2]
    signals = np.zeros(len(probs), dtype=int)
    signals[(p_buy >= threshold) & (p_buy > p_sell)] = 1
    signals[(p_sell >= threshold) & (p_sell > p_buy)] = -1
    return signals


#+-------------------------------------------------------------------+
#| replay                                                            |
#+-------------------------------------------------------------------+
def replay(signals, opens, highs, lows, closes, atr, start: int, stop: int):
    """Replay the bars start..stop-1 and return a list of (pips, exit_reason).
    signals[t - 1] is the decision taken at the close of bar t-1."""
    trades = []
    position = None  # (side, entry_price, stop_price, target_price)

    for t in range(start, stop):
        signal = signals[t - 1]

        # 1 + 2: act on the signal at the open of bar t
        if signal != 0:
            if position is not None and position[0] == -signal:
                trades.append((position[0] * (opens[t] - position[1]) / PIP, "reverse"))
                position = None
            if position is None and not np.isnan(atr[t - 1]):
                entry = opens[t]
                sl_dist = atr[t - 1] * SL_ATR_MULT
                tp_dist = atr[t - 1] * TP_ATR_MULT
                position = (signal, entry, entry - signal * sl_dist, entry + signal * tp_dist)

        # 3: test the range of bar t against the open position
        if position is not None:
            side, entry, sl, tp = position
            hit_sl = lows[t] <= sl if side == 1 else highs[t] >= sl
            hit_tp = highs[t] >= tp if side == 1 else lows[t] <= tp
            if hit_sl:
                trades.append((side * (sl - entry) / PIP, "stop"))
                position = None
            elif hit_tp:
                trades.append((side * (tp - entry) / PIP, "target"))
                position = None

    if position is not None:  # still open at the end of the segment
        trades.append((position[0] * (closes[stop - 1] - position[1]) / PIP, "end"))
    return trades


#+-------------------------------------------------------------------+
#| summarize                                                         |
#+-------------------------------------------------------------------+
def summarize(trades) -> dict:
    pips = np.array([p for p, _ in trades])
    reasons = [r for _, r in trades]
    out = {"trades": len(pips)}
    out.update({f"exit_{r}": reasons.count(r) for r in ("stop", "target", "reverse", "end")})
    if len(pips) == 0:
        return out
    wins, losses = pips[pips > 0], pips[pips < 0]
    equity = np.concatenate(([0.0], np.cumsum(pips)))
    out.update({
        "win_rate": float(len(wins) / len(pips) * 100),
        "profit_factor": float(wins.sum() / abs(losses.sum())) if losses.sum() != 0 else None,
        "net_pips": float(pips.sum()),
        "avg_pips": float(pips.mean()),
        "max_drawdown_pips": float((equity - np.maximum.accumulate(equity)).min()),
    })
    return out


#+-------------------------------------------------------------------+
#| main                                                              |
#+-------------------------------------------------------------------+
def main() -> None:
    df = pd.read_csv(HISTORY_FILE, sep="\t")
    df.columns = df.columns.str.strip()
    opens, highs = df["<OPEN>"].to_numpy(), df["<HIGH>"].to_numpy()
    lows, closes = df["<LOW>"].to_numpy(), df["<CLOSE>"].to_numpy()
    volumes = df["<TICKVOL>"].to_numpy()
    n = len(closes)
    n_train = int(n * TRAIN_FRACTION)
    stamp = df["<DATE>"].astype(str) + " " + df["<TIME>"].astype(str)

    with open(HISTORY_FILE, "rb") as f:
        digest = hashlib.sha256(f.read()).hexdigest()
    print(f"History file: {HISTORY_FILE}  sha256={digest}")
    print(f"Bars: {n}  from {stamp.iloc[0]} to {stamp.iloc[-1]}")
    print(f"In-sample (trained on): bars 0..{n_train - 1}, {stamp.iloc[0]} to {stamp.iloc[n_train - 1]}")
    print(f"Out-of-sample:          bars {n_train}..{n - 1}, {stamp.iloc[n_train]} to {stamp.iloc[-1]}")

    pipeline = joblib.load("model_pipeline.joblib")
    atr = wilder_atr(highs, lows, closes, ATR_PERIOD)
    probs = compute_probabilities(pipeline, closes, volumes)

    segments = {"in-sample": (LOOKBACK, n_train), "out-of-sample": (n_train, n)}
    results = {"history": {"file": HISTORY_FILE, "sha256": digest, "bars": n,
                           "first_bar": stamp.iloc[0], "last_bar": stamp.iloc[-1],
                           "split_bar": n_train, "train_end": stamp.iloc[n_train - 1],
                           "split_time": stamp.iloc[n_train]},
               "segments": {}}
    for name, (start, stop) in segments.items():
        best = np.nanmax(probs[start - 1:stop - 1, [0, 2]], axis=1)
        print(f"\n{name}: bars {start}..{stop - 1}; max(P(Buy), P(Sell)) percentiles "
              f"50/90/99/max = {np.percentile(best, [50, 90, 99, 100]).round(3)}")
        rows = []
        for threshold in THRESHOLDS:
            signals = signals_for(probs, threshold)
            stats = summarize(replay(signals, opens, highs, lows, closes, atr, start, stop))
            stats["threshold"] = threshold
            rows.append(stats)
            if stats["trades"] == 0:
                print(f"  threshold {threshold:.2f}: no trades")
                continue
            pf = "inf" if stats["profit_factor"] is None else f"{stats['profit_factor']:.2f}"
            print(f"  threshold {threshold:.2f}: trades={stats['trades']} win={stats['win_rate']:.1f}% "
                  f"PF={pf} net={stats['net_pips']:+.1f} avg={stats['avg_pips']:+.2f} "
                  f"maxDD={stats['max_drawdown_pips']:.1f} exits stop/target/reverse/end="
                  f"{stats['exit_stop']}/{stats['exit_target']}/{stats['exit_reverse']}/{stats['exit_end']}")
        results["segments"][name] = {"start": start, "stop": stop, "rows": rows}

    with open("replay_results.json", "w") as f:
        json.dump(results, f, indent=2)
    print("\nSaved replay_results.json")


#+-------------------------------------------------------------------+
#| Script entry point                                                |
#+-------------------------------------------------------------------+
if __name__ == "__main__":
    main()
