"""
abcde_test.py -- [2026-10-15] The user: test ideas A-E from the 10/14 (all lost) vs 10/15 (all won) comparison, each ALONE,
on 2 years -- same harness as avoid_rules_test.py (v2_bar_replay.run_stock: the real entry_v2 + exit_v2 code, every
signal, the daily top-30 lists, 0.2% cost).
  A1  market: no buy while IWM is below its 9:30 open          A2  market: no buy while IWM is lower than 30 min ago
  B   clustering (first-order, on the BASE trades): drop a buy that came within 5 min after >= 2 other buys, unless IWM
      is rising over the last 15 min
  C5 / C10   room to the 14-day resistance >= 5% / 10% (v2 min_room_pct; the day-high room kept at the live 1%)
  D25 / D35  volatility stop: stop = lower of the v2 stop and buy x (1 - k x daily ATR%), k = 0.25 / 0.35, max 6% away
  E   crypto stocks (miners / platforms) only while bitcoin is up since 9:30 (Alpaca crypto 1-min bars, cached)
    python3 abcde_test.py [START..END]     -> abcde_test.jsonl + report (abcde_test.log)
"""
import gzip
import json
import sys
from collections import defaultdict
from datetime import datetime, timezone
from pathlib import Path

import numpy as np
import requests

HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE)); sys.path.insert(0, "/var/www/screener/trade")
import v2_bar_replay as R  # noqa: E402

OUT = HERE / "abcde_test.jsonl"
BTC_DIR = R.OW / "btc"
COST = 0.2
CRYPTO = {"CIFR", "CLSK", "RIOT", "CORZ", "MARA", "HUT", "BITF", "WULF", "IREN", "BTDR", "HIVE", "CAN", "BTBT", "GREE",
          "BKKT", "COIN", "GLXY", "CRCL", "BMNR", "SBET", "BTCS", "ARBK", "SOS", "ABTC", "APLD", "BTGO", "DGXX", "SLNH",
          "GRYP", "FUFU", "LMFA", "SDIG", "MIGI", "ANY", "NCTY", "DEFT", "HOLO", "BTOG"}
RUNS = ["BASE", "A1", "A2", "C5", "C10", "D25", "D35", "E"]
CTX = {}
_orig = R.entry_v2.evaluate


def btc_day(day):
    BTC_DIR.mkdir(exist_ok=True)
    f = BTC_DIR / f"{day}.json"
    if f.exists():
        return json.loads(f.read_text())
    from config_loader import get_env
    e = get_env()
    out, tok = {}, None
    while True:
        p = {"symbols": "BTC/USD", "timeframe": "1Min", "start": f"{day}T13:00:00Z", "end": f"{day}T21:00:00Z", "limit": 10000}
        if tok:
            p["page_token"] = tok
        r = requests.get("https://data.alpaca.markets/v1beta3/crypto/us/bars", params=p,
                         headers={"APCA-API-KEY-ID": e.api_key, "APCA-API-SECRET-KEY": e.secret_key}, timeout=30)
        r.raise_for_status(); j = r.json()
        for b in j["bars"].get("BTC/USD", []):
            out[str(R.minute(datetime.fromisoformat(b["t"].replace("Z", "+00:00"))))] = b["c"]
        tok = j.get("next_page_token")
        if not tok:
            break
    f.write_text(json.dumps(out))
    return out


def series(rows):
    """IWM close per minute 0..389 (carry forward)."""
    arr, last = [None] * 390, None
    by = {R.minute(datetime.fromtimestamp(r[0], timezone.utc)): r[4] for r in rows}
    o = rows[0][1] if rows else None
    for m in range(390):
        last = by.get(m, last)
        arr[m] = last
    return o, arr


def wrapped(sym, view, ref, f15, pers, as_of=None, cfg=None, quote=None):
    d = _orig(sym, view, ref, f15, pers, as_of=as_of, cfg=cfg, quote=quote)
    if not d.should_enter:
        return d
    run = CTX["run"]; m = R.minute(as_of) - 1          # the decision bar (the buy is at the next open)
    iwm_o, iwm = CTX["iwm"]
    block = False
    if run == "A1" and iwm_o and iwm[m] is not None and iwm[m] < iwm_o:
        block = True
    if run == "A2" and m >= 30 and iwm[m] is not None and iwm[m - 30] is not None and iwm[m] < iwm[m - 30]:
        block = True
    if run == "E" and sym in CRYPTO:
        b = CTX["btc"]; b0 = b.get("0")
        bm = next((b[str(k)] for k in range(m, max(-1, m - 10), -1) if str(k) in b), None)
        if b0 is None or bm is None or bm <= b0:
            block = True
    if run in ("D25", "D35") and ref.get("atr14") and ref.get("prev_close"):
        k = 0.25 if run == "D25" else 0.35
        price = d.metrics["price"]
        vs = price * (1 - min(6.0, k * ref["atr14"] / ref["prev_close"] * 100) / 100)
        st = d.metrics.get("stage3", {}).get("stop")
        if st:
            d.metrics["stage3"]["stop"] = min(st, vs)
    if block:
        d.should_enter = False
    return d


R.entry_v2.evaluate = wrapped


def run(rng):
    a, b = rng.split("..")
    cfg = R.get_config()
    base_e = {**(cfg.get("entry_v2") or {}), "confirm_checks": 1}
    xcfg = {**(cfg.get("exit_v2") or {}), "enabled": True}
    with open(OUT, "w") as out:
        for p in sorted(R.OW.glob("bars/bars_20*.json.gz")):
            day = p.name[5:15]
            if not (a <= day <= b):
                continue
            d = json.load(gzip.open(p, "rt")); bench = R.bench_pct(day)
            bf = R.OW / "bars" / f"bench_{day}.json.gz"
            CTX["iwm"] = series(json.load(gzip.open(bf, "rt")).get("IWM", [])) if bf.exists() else (None, [None] * 390)
            try:
                CTX["btc"] = btc_day(day)
            except Exception as e:
                CTX["btc"] = {}; print(day, "btc error", e, flush=True)
            k = defaultdict(int)
            for s in d["top30_current"]:
                fp = R.OW / "flow" / day / f"{s}.json"
                ref = R.REF.load(day, s)
                if s not in d["symbols"] or not fp.exists() or not ref:
                    continue
                flow = json.loads(fp.read_text())
                for rn in RUNS:
                    CTX["run"] = rn
                    ecfg = dict(base_e)
                    if rn in ("C5", "C10"):
                        ecfg.update(min_room_pct=5.0 if rn == "C5" else 10.0, day_high_min_room=base_e.get("min_room_pct", 1.0))
                    for t in R.run_stock(day, s, d["symbols"][s]["bars"], flow, ref, bench, ecfg, xcfg):
                        bm = t["buy_m"]; io, iw = CTX["iwm"]
                        out.write(json.dumps({"run": rn, "day": day, "sym": s, "buy_m": bm, "pl_gross": t["pl"] + R.COST,
                                              "iwm15": (iw[bm - 1] / iw[bm - 16] - 1) * 100 if bm >= 16 and iw[bm - 1] and iw[bm - 16] else None,
                                              "crypto": s in CRYPTO}) + "\n")
                        k[rn] += 1
            R.REF._CACHE.clear(); del d
            print(day, k.get("BASE", 0), "base trades", flush=True)
    print("ABCDE_DONE")


def report():
    T = [json.loads(l) for l in open(OUT)]
    days = sorted({t["day"] for t in T}); half = days[len(days) // 2]
    pl = lambda X: np.array([t["pl_gross"] - COST for t in X])
    print(f"{len(days)} days {days[0]}..{days[-1]}; per trade after {COST}% cost; every v2 signal, no slot limit\n")
    print(f"   {'run':34} {'trades':>7} {'per trade':>10} {'total':>9} {'win':>5} | {'half 1':>8} {'half 2':>8}")
    def line(lab, X):
        p = pl(X); h = np.array([t["day"] < half for t in X])
        print(f"   {lab:34} {len(p):7} {p.mean():+9.3f}% {p.sum():+8.1f}% {np.mean(p > 0):4.0%} | {p[h].mean():+7.3f}% {p[~h].mean():+7.3f}%")
    names = {"BASE": "BASE (live rules)", "A1": "A1 no buy while IWM < its open", "A2": "A2 no buy while IWM falling 30 min",
             "C5": "C5 room to resistance >= 5%", "C10": "C10 room to resistance >= 10%", "D25": "D25 stop >= 0.25 x daily ATR",
             "D35": "D35 stop >= 0.35 x daily ATR", "E": "E crypto only while BTC up"}
    for r in RUNS:
        X = [t for t in T if t["run"] == r]
        if X:
            line(names[r], X)
        else:
            print(f"   {names[r]:34} {0:7}  (blocks every buy)")
    base = sorted([t for t in T if t["run"] == "BASE"], key=lambda t: (t["day"], t["buy_m"]))
    keep = []
    for t in base:
        near = sum(1 for u in base if u is not t and u["day"] == t["day"] and 0 <= t["buy_m"] - u["buy_m"] <= 5)
        if near >= 2 and not (t["iwm15"] is not None and t["iwm15"] > 0):
            continue
        keep.append(t)
    line("B  clustered buys only if IWM rising (1st-order)", keep)
    cl = [t for t in base if t not in keep]
    if cl:
        line("   (the clustered buys B removes)", cl)
    cr = [t for t in base if t["crypto"]]
    if cr:
        line("   (base: crypto stocks only)", cr)
        line("   (E: crypto stocks only)", [t for t in T if t["run"] == "E" and t["crypto"]])


if __name__ == "__main__":
    if "--report" in sys.argv:
        report()
    else:
        run(sys.argv[1] if len(sys.argv) > 1 else "2024-10-01..2026-10-02")
        report()
