"""pattern_score.py A..B OUT -- [2026-10-28] SCORECARD of the 40 opening patterns (trade/opening_patterns.py) on the library (old-score
top 30, 1-min bars, data/reference-style refs). For every confirmed pattern and every 10th minute (random baseline, 9:35-11:30), measured
from the buy price (next open): close 15 / 30 / 60 min later, max rise / max drop within 15 / 60 min, +1% vs -1% and +2% vs -2% first.
summary: python3 pattern_score.py summary OUT1 [OUT2..] -> per pattern, year 1 vs year 2, vs random."""
import gzip, json, sys
from pathlib import Path
import numpy as np
HERE = Path(__file__).resolve().parent
sys.path.insert(0, "/var/www/screener/trade/reports/playbook"); sys.path.insert(0, "/var/www/screener/trade")
def meas(b, bi, P):
    def first(x):
        for z in b[bi:bi + 120]:
            if z["l"] <= P * (1 - x / 100): return -1
            if z["h"] >= P * (1 + x / 100): return 1
        return 0
    cl = lambda n: (b[min(bi + n - 1, len(b) - 1)]["c"] / P - 1) * 100
    w15, w60 = b[bi:bi + 15], b[bi:bi + 60]
    return dict(c15=round(cl(15), 3), c30=round(cl(30), 3), c60=round(cl(60), 3), r15=round((max(z["h"] for z in w15) / P - 1) * 100, 3),
                d15=round((min(z["l"] for z in w15) / P - 1) * 100, 3), r60=round((max(z["h"] for z in w60) / P - 1) * 100, 3),
                d60=round((min(z["l"] for z in w60) / P - 1) * 100, 3), f1=first(1), f2=first(2))
if sys.argv[1] != "summary":
    import v2_bar_replay as R
    import opening_patterns as OP
    a, b_ = sys.argv[1].split(".."); out = open(sys.argv[2], "w"); nd = 0
    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"))
        for s in d["top30_current"]:
            ref = R.REF.load(day, s)
            if s not in d["symbols"] or not ref or not ref.get("prev_close") or not ref.get("atr14"): continue
            bars = [x for x in R.bars_of(d["symbols"][s]["bars"]) if 0 <= R.minute(x["t"]) < 390]
            if len(bars) < 120: continue
            idx = {R.minute(x["t"]): i for i, x in enumerate(bars)}
            Rz, ev = OP.analyze_day(bars, ref, R.minute)
            if Rz is None: continue
            for t, pid, px in ev:
                i = idx.get(t)
                if i is None or i + 1 >= len(bars): continue
                out.write(json.dumps(dict(day=day, sym=s, pid=pid, t=t, ctx=Rz.ctx, **meas(bars, i + 1, bars[i + 1]["o"]))) + "\n")
            for t in range(5, 121, 10):
                i = idx.get(t)
                if i is not None and i + 1 < len(bars):
                    out.write(json.dumps(dict(day=day, sym=s, pid=0, t=t, ctx=Rz.ctx, **meas(bars, i + 1, bars[i + 1]["o"]))) + "\n")
        del d; R.REF._CACHE.clear(); nd += 1; out.flush(); print(day, nd, flush=True)
    out.close(); print("PSCORE_DONE")
else:
    sys.path.insert(0, "/var/www/screener/trade"); import opening_patterns as OP
    X = [json.loads(l) for f in sys.argv[2:] for l in open(f)]
    def f(Z):
        if not Z: return "n     0"
        a = lambda k: np.mean([z[k] for z in Z])
        return (f"n {len(Z):6} | up after 15m {np.mean([z['c15'] > 0 for z in Z]):3.0%} avg 15m {a('c15'):+.2f}% 60m {a('c60'):+.2f}% | rise/drop 60m "
                f"{a('r60'):+.2f}/{a('d60'):+.2f} ({a('r60') / max(-a('d60'), 1e-9):.2f}) | +2%/-2% first {np.mean([z['f2'] == 1 for z in Z]):3.0%}/{np.mean([z['f2'] == -1 for z in Z]):3.0%}")
    Y1 = lambda Z: [z for z in Z if z["day"] < "2025-10-01"]; Y2 = lambda Z: [z for z in Z if z["day"] >= "2025-10-01"]
    print(f"{len(X)} rows, {X[0]['day']} .. {X[-1]['day']}; year 1 < 2025-10-01 <= year 2; measured from the next open after confirmation\n")
    base = [x for x in X if x["pid"] == 0]
    print(f"RANDOM minute 9:35-11:30\n   y1 {f(Y1(base))}\n   y2 {f(Y2(base))}")
    for pid, (g, nm, bias, rule) in OP.CATALOG.items():
        Z = [x for x in X if x["pid"] == pid]
        print(f"#{pid:2} {g} {nm} [{bias}]\n   y1 {f(Y1(Z))}\n   y2 {f(Y2(Z))}")
    print("PSUMMARY_DONE")
