"""
momentum_cross.py -- [2026-10-22] the user: cross the MOMENTUM indicators with the BLOCKERS so the override works for each
stock individually. Every minute (9:35-14:30) of every top-30 stock where the 5-bar signal fires (momentum_entry.signal):
  blockers   momentum_entry.blockers (hard / extended / soft) incl. S2 / S3 / S6 / S8 / S9 from the situation code
  momentum   in plain % AND in the stock's own terms:
               push5 %            push5 in daily ATRs       push5 in 1-min ranges (mean high-low of the last 15 bars)
               range position     VWAP %   VWAP in ATRs     vol5 x normal (the stock's own volume curve)
               bs3 / bs5          up bars of 5              higher lows
  outcome    a buy at the next open: +1% / -1% bracket in 60 min (EV after 0.2% cost) AND a stock-scaled bracket
             +/- 0.15 x daily ATR (EV_atr after cost), 30-min best / worst / return
Report: per soft blocker, EV of the signal minutes with that blocker, split by each momentum indicator (both scales),
both halves -> which momentum level justifies overruling WHICH blocker.
    nice -n 19 python3 momentum_cross.py [START..END]   -> momentum_cross.jsonl + momentum_cross.log
"""
import gzip
import json
import sys
from collections import defaultdict
from pathlib import Path

import numpy as np

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
import entry_situations as ES  # noqa: E402
import momentum_entry as ME  # noqa: E402
import logging  # noqa: E402
logging.getLogger("trade_bot.entry_situations").setLevel(logging.WARNING)

OUT = HERE / "momentum_cross.jsonl"
SIT = {"S2_spike_confirm": {"enabled": True, "record_only": False},
       "S3_block_print": {"enabled": True, "record_only": False, "mode": "while_in_window"},
       "S6_extended": {"enabled": True, "record_only": False, "mode": "pct", "max_pct": 3.0},
       "S8_resistance": {"enabled": True, "record_only": False, "mode": "pct", "min_room_pct": 5.0},
       "S9_prev_close": {"enabled": True, "record_only": False}}


def outcome(bars, m, atrp):
    P = bars[m + 1]["o"]
    e = min(m + 61, len(bars) - 1)
    res = {}
    for lab, up, dn in (("ev", 1.0, 1.0), ("ev_atr", 0.15 * atrp, 0.15 * atrp), ("ev2", 2.0, 1.0)):
        r = None
        for j in range(m + 1, e + 1):
            hit_dn = bars[j]["l"] <= P * (1 - dn / 100); hit_up = bars[j]["h"] >= P * (1 + up / 100)
            if hit_dn:
                r = -dn; break
            if hit_up:
                r = up; break
        if r is None:
            r = (bars[e]["c"] / P - 1) * 100
        res[lab] = r - 0.2
        if lab in ("ev", "ev2"):
            res["hit" + ("1" if lab == "ev" else "2")] = r == up
    e30 = min(m + 31, len(bars) - 1)
    res.update(best30=(max(b["h"] for b in bars[m + 1:e30 + 1]) / P - 1) * 100,
               worst30=(min(b["l"] for b in bars[m + 1:e30 + 1]) / P - 1) * 100, ret30=(bars[e30]["c"] / P - 1) * 100)
    return res


def run(rng):
    a, b = rng.split("..")
    cfg = R.get_config(); ecfg = {**(cfg.get("entry_v2") or {}), "confirm_checks": 1}
    c = ME.DEFAULTS
    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")); n = 0
            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 or not ref.get("atr14"):
                    continue
                fl = json.loads(fp.read_text()); fb, fs = fl["buy"], fl["sell"]
                bars = [x for x in R.bars_of(d["symbols"][s]["bars"]) if 0 <= R.minute(x["t"]) < 390]
                if len(bars) < 120:
                    continue
                atrp = ref["atr14"] / ref["prev_close"] * 100
                vpm = ref.get("vol_per_min") or []
                for z in (ES._hist, ES._pending, ES._streak, ES._s1, ES._s2, ES._s3):
                    z.clear()
                for i in range(5, len(bars) - 2):
                    m = R.minute(bars[i]["t"])
                    if m < 4 or m >= 300:
                        continue
                    done = bars[:i + 1]
                    flow5 = [(fb[k], fs[k]) for k in range(m - 4, m + 1)]
                    ok, sinfo = ME.signal(done, flow5, c)
                    if not ok:
                        continue
                    view = done + [{"t": bars[i + 1]["t"], "o": bars[i + 1]["o"], "h": bars[i + 1]["o"], "l": bars[i + 1]["o"], "c": bars[i + 1]["o"], "v": 0.0}]
                    lo = max(0, m - 14)
                    dv = R.entry_v2.evaluate(s, view, ref, (sum(fb[lo:m + 1]), sum(fs[lo:m + 1])), {}, as_of=bars[i + 1]["t"], cfg=ecfg, quote=None)
                    held = []
                    if len(done) >= 20:
                        fm = {k: (fb[k], fs[k]) for k in range(0, m + 1)}
                        tags, det = ES.tag(day, s, m, view, ref, dv.metrics, cfg=SIT, flow_by_min=fm); det["_flowm"] = fm
                        held = [h.split(" ")[0] for h in ES.check(day, s, m, view, ref, dv.metrics, tags, det, cfg=SIT)]
                    hard, ext, soft = ME.blockers(done, ref, m, dv.metrics, held, None, c)
                    _, mi = ME.momentum(done, ref, m, c)
                    r1 = sum(x["h"] - x["l"] for x in done[-15:]) / min(15, len(done))
                    P = done[-1]["c"]; push = mi["push"]
                    bs = lambda k0, k1: (sum(fb[k0:k1]) / max(sum(fb[k0:k1]) + sum(fs[k0:k1]), 1e-9))
                    k_up = 0
                    for j in range(len(done) - 1, 0, -1):          # consecutive bars closing higher (the rise so far)
                        if done[j]["c"] > done[j - 1]["c"]:
                            k_up += 1
                        else:
                            break
                    lo_j = min(range(max(0, len(done) - 30), len(done)), key=lambda j: done[j]["l"])
                    sp = dv.metrics.get("sr14") or {}
                    dhi = max(x["h"] for x in done[:-1]) if len(done) > 1 else P
                    pc = ref.get("prev_close")
                    room_pc = (pc / P - 1) * 100 if pc and pc > P else None
                    rooms = [x for x in (sp.get("dist_to_resistance_pct") if not sp.get("above_14d_high") else None,
                                         (dhi / P - 1) * 100 if dhi > P else None, room_pc) if x is not None]
                    rec = {"day": day, "sym": s, "m": m, "atr": atrp, "hard": hard, "ext": ext, "soft": soft,
                           "k_up": k_up, "bars_from_low": len(done) - 1 - lo_j, "rise_from_low": (P / done[lo_j]["l"] - 1) * 100,
                           "rise_r1": (P - done[lo_j]["l"]) / r1 if r1 > 0 else None,
                           "room_res": sp.get("dist_to_resistance_pct") if not sp.get("above_14d_high") else 99.0,
                           "room_dayhi": (dhi / P - 1) * 100 if dhi > P else 0.0, "room_any": min(rooms) if rooms else 99.0,
                           "push": push, "push_atr": push / atrp, "push_r1": (P - done[-6]["c"]) / r1 if r1 > 0 and len(done) >= 6 else None,
                           "rpos": mi["range_pos"], "vwap": mi["vwap_pct"], "vwap_atr": mi["vwap_pct"] / atrp, "vol5x": mi["vol5_x"],
                           "bs3": bs(m - 2, m + 1), "bs5": bs(m - 4, m + 1),
                           "up5": sum(1 for x in done[-5:] if x["c"] > x["o"]),
                           "hl": len(done) >= 10 and min(x["l"] for x in done[-5:]) > min(x["l"] for x in done[-10:-5]),
                           **outcome(bars, i, atrp)}
                    out.write(json.dumps(rec) + "\n"); n += 1
                R.REF._CACHE.clear()
            del d
            print(day, n, flush=True)
    report()


def report():
    T = [json.loads(l) for l in open(OUT)]
    days = sorted({t["day"] for t in T}); half = days[len(days) // 2]
    def line(lab, X, ind=3):
        if len(X) < 40:
            return
        e = np.array([t["ev"] for t in X]); ea = np.array([t["ev_atr"] for t in X]); h = np.array([t["day"] < half for t in X])
        print(f"{' ' * ind}{lab:38} {len(X):6} | EV {e.mean():+.3f}% (h1 {e[h].mean() if h.any() else 0:+.3f} h2 {e[~h].mean() if (~h).any() else 0:+.3f}) "
              f"| EV stock-scaled {ea.mean():+.3f}% (h1 {ea[h].mean() if h.any() else 0:+.3f} h2 {ea[~h].mean() if (~h).any() else 0:+.3f})")
    print(f"\n{len(T)} signal minutes, {len(days)} days {days[0]}..{days[-1]}. EV = +1%/-1% bracket (60 min) after 0.2% cost; "
          f"stock-scaled = +/-0.15 x daily ATR bracket after cost")
    line("ALL signal minutes", T, 0)
    line("no blocker at all", [t for t in T if not t["hard"] and not t["ext"] and not t["soft"]], 0)
    line("HARD blocked", [t for t in T if t["hard"]], 0)
    line("EXTENDED (no hard)", [t for t in T if t["ext"] and not t["hard"]], 0)
    S = [t for t in T if not t["hard"] and not t["ext"] and t["soft"]]
    line("SOFT only", S, 0)
    IND = [("push %", "push", [-9, 0.25, 0.5, 1, 2, 99]), ("push in daily ATRs", "push_atr", [-9, 0.03, 0.06, 0.1, 0.2, 9]),
           ("push in 1-min ranges", "push_r1", [-99, 1, 2, 3, 5, 999]), ("range position", "rpos", [0, 0.35, 0.5, 0.65, 0.8, 1.01]),
           ("VWAP %", "vwap", [-99, 0, 0.5, 1, 2, 99]), ("VWAP in daily ATRs", "vwap_atr", [-9, 0, 0.05, 0.1, 0.2, 9]),
           ("vol5 x normal", "vol5x", [0, 1, 1.5, 2.5, 5, 999]), ("buy share 3 min", "bs3", [0, 0.55, 0.65, 0.75, 1.01]),
           ("up bars of 5", "up5", [0, 3, 4, 6])]
    blk = sorted({b for t in S for b in t["soft"]}, key=lambda b: -sum(1 for t in S if b in t["soft"]))
    for bk in blk:
        X = [t for t in S if bk in t["soft"]]
        print(f"\n== SOFT blocker: {bk}  (signal minutes with it, no hard / extended)")
        line("all", X)
        line("ONLY this blocker", [t for t in X if t["soft"] == [bk]])
        for nm, k, cuts in IND:
            print(f"   {nm}:")
            for lo, hi in zip(cuts, cuts[1:]):
                line(f"{lo:g}..{hi:g}", [t for t in X if t.get(k) is not None and lo <= t[k] < hi], 6)
        line("higher lows", [t for t in X if t["hl"]], 3)
    spec_report()
    print("MOMCROSS_DONE")


def spec_report():
    """[2026-10-22] the user's spec: recognize the rise -> how many bars confirm it (per stock behavior) -> place in range ->
    room to profit -> buyers in control. Score = reaching +1% / +2% before -1% (60 min), whatever the stock did that day."""
    T = [json.loads(l) for l in open(OUT)]
    T = [t for t in T if "k_up" in t]
    days = sorted({t["day"] for t in T}); half = days[len(days) // 2]
    def line(lab, X, ind=4):
        if len(X) < 40:
            return
        h1 = np.array([t["hit1"] for t in X]); h2 = np.array([t["hit2"] for t in X]); e = np.array([t["ev"] for t in X])
        y = np.array([t["day"] < half for t in X])
        print(f"{' ' * ind}{lab:34} {len(X):6} | +1% first {h1.mean():4.0%} (h1 {h1[y].mean() if y.any() else 0:4.0%} h2 {h1[~y].mean() if (~y).any() else 0:4.0%}) "
              f"| +2% before -1% {h2.mean():4.0%} | EV(+-1%) {e.mean():+.3f}%")
    vol = [("calm ATR < 6%", 0, 6), ("medium ATR 6-10%", 6, 10), ("volatile ATR >= 10%", 10, 999)]
    print(f"\n===== THE USER'S SPEC (score: +1% / +2% reached before -1%, 60 min; after 0.2% cost for EV) =====")
    line("ALL signal minutes", T, 0)
    for lab, a, b in vol:
        X = [t for t in T if a <= t["atr"] < b]
        print(f"\n-- {lab}")
        line("all", X)
        print("    step 2 CONFIRMATION: rising bars in a row")
        for k in (1, 2, 3, 4, 6):
            line(f"{k}{'+' if k == 6 else ''} bars up", [t for t in X if (t["k_up"] >= 6 if k == 6 else t["k_up"] == k)], 6)
        print("    step 2b how far it rose from the 30-min low, in its own 1-min ranges")
        for lo, hi in ((0, 2), (2, 4), (4, 7), (7, 12), (12, 999)):
            line(f"{lo}-{hi} ranges", [t for t in X if t.get("rise_r1") is not None and lo <= t["rise_r1"] < hi], 6)
        print("    step 3 PLACE IN TODAY'S RANGE")
        for lo, hi in ((0, 0.35), (0.35, 0.5), (0.5, 0.65), (0.65, 0.8), (0.8, 1.01)):
            line(f"{lo:g}-{hi:g}", [t for t in X if lo <= t["rpos"] < hi], 6)
        print("    step 4 ROOM above (nearest of: 14-day resistance, today's high, previous close)")
        for lo, hi in ((0, 1), (1, 2), (2, 3), (3, 5), (5, 99.5)):
            line(f"{lo}-{hi}%" if hi < 99 else "5%+ / no level", [t for t in X if lo <= t["room_any"] < hi], 6)
        print("    step 5 BUYERS IN CONTROL (buy share last 3 min)")
        for lo, hi in ((0.5, 0.6), (0.6, 0.7), (0.7, 0.8), (0.8, 1.01)):
            line(f"{lo:g}-{hi:g}", [t for t in X if lo <= t["bs3"] < hi], 6)
    print("SPEC_DONE")


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