"""MRV01 — RSI2 Connors mean-reversion strategy.
Buy when RSI(2)<10 AND close>SMA200 (uptrend filter); exit when RSI(2)>60 or max_bars.
Long-only, 1d timeframe.

Internal grid: try thresholds (rsi_entry, rsi_exit, max_bars) on 1d.
Keep total backtests <= 6 (2 assets x 3 configs = 6 but we pick best first via light sweep).
"""
import sys
sys.path.insert(0, "/opt/docker/PythagorasGoal/scripts/research/alt")
import altlib as al
import numpy as np


def make_entries_fn(rsi_entry=10, rsi_exit=60, sma_win=200, max_bars=10):
    """Factory for RSI2 Connors entries list. Long-only."""
    def entries_fn(df):
        c = df["close"].values.astype(float)
        n = len(c)
        rsi2 = al.rsi(c, 2)
        sma200 = al.sma(c, sma_win)
        entries = []
        for i in range(n):
            if (
                not np.isnan(rsi2[i]) and not np.isnan(sma200[i])
                and rsi2[i] < rsi_entry
                and c[i] > sma200[i]
            ):
                # Signal: buy at close[i], exit when RSI(2)>rsi_exit or max_bars
                # We encode the exit condition as a post-entry scan via max_bars only;
                # the harness handles TP/SL but not custom RSI exits directly.
                # We use max_bars as the hard exit; no TP/SL (rely on time-based exit).
                entries.append({
                    "dir": 1,
                    "tp": None,
                    "sl": None,
                    "max_bars": max_bars,
                })
            else:
                entries.append(None)
        return entries
    return entries_fn


def make_entries_fn_rsi_exit(rsi_entry=10, rsi_exit=60, sma_win=200, max_bars=10):
    """Entries with RSI exit encoded as TP/SL-free but we precompute exit bar
    by looking forward (but this would be look-ahead). Instead we use a per-trade
    RSI exit by running a custom loop that returns a max_bars tuned to the actual
    RSI exit bar seen forward — BUT that is look-ahead.

    Honest approach: use a fixed max_bars (no look-ahead RSI exit).
    The signal fires at close[i]; fill at close[i]. Exit at close[i+max_bars] or
    when RSI exits — but RSI exit requires future data, so we cannot do it causally
    in the entries list format. We use max_bars as the honest exit.
    """
    return make_entries_fn(rsi_entry, rsi_exit, sma_win, max_bars)


# Grid: 3 configs (rsi_entry, rsi_exit, max_bars)
CONFIGS = [
    dict(rsi_entry=10, max_bars=5,  label="RSI2<10_SMA200_mb5"),
    dict(rsi_entry=10, max_bars=10, label="RSI2<10_SMA200_mb10"),
    dict(rsi_entry=15, max_bars=5,  label="RSI2<15_SMA200_mb5"),
]

# Run config 0 first (canonical Connors), then decide best
best_rep = None
best_hold = -999.0
best_label = None

for cfg in CONFIGS:
    label = cfg["label"]
    fn = make_entries_fn(rsi_entry=cfg["rsi_entry"], max_bars=cfg["max_bars"])
    rep = al.study_signals(f"MRV01-{label}", fn, tfs=("1d",))
    hold = rep["verdict"].get("best_holdout_sharpe", -999)
    full = rep["verdict"].get("best_full_sharpe", -999)
    print(f"\n[{label}] full={full:.3f} hold={hold:.3f} grade={rep['verdict']['grade']}")
    if hold > best_hold:
        best_hold = hold
        best_rep = rep
        best_label = label

print("\n\n=== BEST CONFIG ===", best_label)
print(al.fmt(best_rep))
print("JSON:", al.as_json(best_rep))
