"""r12_test.py -- [2026-10-25] R12 "turn at VWAP / the open" (G10, test copy of r11_test.py): (1) recall on the user's marks (practice/groups/G8_marks.json), (2) every
trigger on 2024-26 (library = old-score top 30, quote flow) and 2016-18 (top30_10y, tick flow), buy at the next open, stop under
the low (x0.998, 0.5-4%), exits C3 and LV (level exit, then C3 above VWAP), 0.2% cost.   python3 r11_test.py marks|lib|10y"""
import gzip, 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 r12_setup as r11_setup, exit_x1
from queue_test import Day, c3
from sim_full import loader
from sim_2y import sim as c3_sim
COST = 0.2
GRID = {f"tn{tn}_b5{int(b5*100)}_nv{nv}_om{om}": {"turn_need": tn, "bs5_min": b5, "near_vwap": nv, "off_max": om}
        for tn in (1, 2) for b5 in (0.45, 0.50) for nv in (1.0, 1.5, 2.5) for om in (3.0, 5.0)}
LOOSE = {"turn_need": 1, "bs5_min": 0.45, "near_vwap": 2.5, "off_max": 5.0}


def lv_sim(D, bi, P, stop, info):
    """level exit: target = nearest of VWAP / open / prev close > P*1.005; a stall there (bar reaches >= target*0.997 then a close
    under the bar before) -> sell next open; a close > VWAP*1.005 -> hand over to C3 (GB2 + X1 control)."""
    lv = sorted(x for x in (info.get("vwap"), info.get("open"), info.get("prev_close")) if x and x > P * 1.005)
    if not lv:
        return c3_sim(D, bi, P, stop, 2.0, "C3")
    T = lv[0]; reached = False; bars, mins = D.b, D.m
    for j in range(bi, len(bars)):
        b = bars[j]
        if b["l"] <= stop:
            return (min(stop, b["o"]) if j > bi else stop) / P * 100 - 100 - COST, j, "stop"
        if mins[j] >= 385:
            return b["c"] / P * 100 - 100 - COST, j, "15:55"
        if b["c"] > D.vw[j] * 1.005:
            pl, jj, why = c3_sim(D, j + 1, P, stop, 2.0, "C3") if j + 1 < len(bars) else (b["c"] / P * 100 - 100 - COST, j, "end")
            return pl, jj, "C3 after VWAP: " + why
        if b["h"] >= T * 0.997:
            reached = True
        if reached and j > bi and b["c"] < bars[j - 1]["c"] and j + 1 < len(bars):
            return bars[j + 1]["o"] / P * 100 - 100 - COST, j + 1, "level stall"
    return bars[-1]["c"] / P * 100 - 100 - COST, len(bars) - 1, "end"


def scan(D, cfgs, out, day, s, elig=None):
    last = {}
    for i in range(6, len(D.b) - 1):
        m = D.m[i]
        if m > 330:
            break
        done = D.b[:i + 1]
        ok, _ = r11_setup.check(done, D.fl, D.ref, m, LOOSE)
        if not ok:
            continue
        for k, c in cfgs.items():
            if m - last.get(k, -9999) < r11_setup.DEFAULTS["cooldown"]:
                continue
            ok, info = r11_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
            a = c3_sim(D, i + 1, P, stop, 2.0, "C3"); b = lv_sim(D, i + 1, P, stop, info)
            out.append({"var": k, "day": day, "sym": s, "m": m, "c3": round(a[0], 3), "lv": round(b[0], 3), "lv_why": b[2][:20],
                        "low_vs_vwap": info["low_vs_vwap"], "off": info["off_low"]})


def main():
    part = sys.argv[1]; out = []
    if part == "marks":
        M = json.load(open("/var/www/screener/trade/reports/practice/groups/G8_marks.json"))
        for k, x in sorted(M.items(), key=lambda z: int(z[0])):
            d = json.load(gzip.open(R.OW / "bars" / f"bars_{x['day']}.json.gz", "rt")); s = x["sym"]
            b = [y for y in R.bars_of(d["symbols"][s]["bars"]) if 0 <= R.minute(y["t"]) < 390]
            D = Day(b, [R.minute(y["t"]) for y in b], json.loads((R.OW / "flow" / x["day"] / f"{s}.json").read_text()), R.REF.load(x["day"], s) or {})
            trig = []
            for i in range(6, len(b) - 1):
                ok, info = r11_setup.check(b[:i + 1], D.fl, D.ref, D.m[i])
                if ok:
                    trig.append(f"{9 + (30 + D.m[i]) // 60}:{(30 + D.m[i]) % 60:02d}")
            print(f"#{k:2} {s:5} {x['day']} user: {x['entry'] if isinstance(x['entry'], str) else ' | '.join(x['entry'])}\n      R11 (default) fires at: {', '.join(trig) or 'NEVER'}")
            R.REF._CACHE.clear()
        return
    if part == "lib":
        for p in sorted(R.OW.glob("bars/bars_20*.json.gz")):
            day = p.name[5:15]
            if not ("2024-10-01" <= day <= "2026-10-02"):
                continue
            d = json.load(gzip.open(p, "rt"))
            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
                b = [y for y in R.bars_of(d["symbols"][s]["bars"]) if 0 <= R.minute(y["t"]) < 390]
                if len(b) < 100:
                    continue
                scan(Day(b, [R.minute(y["t"]) for y in b], json.loads(fp.read_text()), ref), GRID, out, day, s)
            R.REF._CACHE.clear(); print(day, len(out), flush=True)
    else:
        days, load_day = loader("10y", "tick")
        for day in days():
            if day > "2018-11-23":
                continue
            for s, D in load_day(day):
                scan(D, GRID, out, day, s)
            R.REF._CACHE.clear(); print(day, len(out), flush=True)
    json.dump(out, open(HERE / f"r12_{part}.json", "w")); print("R12_DONE")


if __name__ == "__main__":
    main()
