"""r10_test.py -- [2026-10-25] R10 (gap-down recovery reclaims VWAP) on both periods, NO look-ahead, buy at the next open, stop
under the 15-bar low (x0.998, clamped 0.5-4%), C3 exit (GB2 + X1 control), 0.2% cost. Per-trigger results (no account limits).
  A star     2024-10..2026-10, the Star bot's lists (9:28 v1 top 50 + 5-min intraday rescans; a stock is eligible only while listed)
  B v1-30    2024-10..2026-10, the trade bot's new list (old score top 30 at 9:28) = lists_v1 cut to 30
  C 2016-18  first 2 of the 10 years, v3 top 30 (no rescan data exists there)
    python3 r10_test.py A|B|C   -> r10_<X>.json"""
import itertools, json, sys
from pathlib import Path
HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE)); sys.path.insert(0, "/var/www/screener/trade/reports/playbook"); sys.path.insert(0, "/var/www/screener/trade")
import v2_bar_replay as R
import r10_setup
from sim_full import loader, star_loader
from sim_2y import sim as exit_sim
GRID = {f"rm{rm}_ch{ch}_bs{int(bs * 100)}": {"reclaim_max": rm, "ch15_min": ch, "bs15_min": bs}
        for rm in (1.0, 1.5, 2.5) for ch in (0.5, 1.0, 1.5) for bs in (0.45, 0.50, 0.55)}
part = sys.argv[1]
if part == "A":
    days, load_day = star_loader("star_lists")
elif part == "B":
    import json as _j, shutil
    d30 = HERE / "lists_v1_30"; d30.mkdir(exist_ok=True)
    for f in (HERE / "lists_v1").glob("*.json"):
        L = _j.loads(f.read_text()); L["pre"] = L["pre"][:30]; L["union"] = L["pre"]; L["ref"] = {s: L["ref"][s] for s in L["pre"]}
        (d30 / f.name).write_text(_j.dumps(L))
    import sim_full
    sim_full.star_loader.__defaults__ = ("lists_v1_30",)
    days, load_day = star_loader("lists_v1_30")
else:
    days, load_day = loader("10y", "tick")
out = []
for day in days():
    if part == "C" and day > "2018-11-23":
        continue
    for s, D in load_day(day):
        elig = getattr(D, "elig", None); last = {}
        for i in range(16, len(D.b) - 1):
            m = D.m[i]
            if m > 120:
                break
            if elig is not None and not elig(m + 1):
                continue
            done = D.b[:i + 1]
            base_ok, info0 = r10_setup.check(done, D.fl, D.ref, m, {"reclaim_max": 2.5, "ch15_min": 0.5, "bs15_min": 0.45})
            if not base_ok:
                continue
            for k, c in GRID.items():
                if m - last.get(k, -9999) < r10_setup.DEFAULTS["cooldown"]:
                    continue
                ok, info = r10_setup.check(done, D.fl, D.ref, m, c)
                if not ok:
                    continue
                last[k] = m
                P = D.b[i + 1]["o"]; stop = min(max(info["support"] * 0.998, P * 0.96), P * 0.995)
                if P <= stop:
                    continue
                pl, j, why = exit_sim(D, i + 1, P, stop, 2.0, "C3")
                out.append({"var": k, "day": day, "sym": s, "m": m, "pl": round(pl, 3), "why": why, **{kk: info[kk] for kk in ("gap", "vs_vwap", "ch15", "bs15", "rvol")}})
    R.REF._CACHE.clear()
    print(day, len(out), flush=True)
json.dump(out, open(HERE / f"r10_{part}.json", "w"))
print("R10_DONE")
