"""
v2_bar_replay.py -- [2026-10-05] ENTRY RESEARCH ON 2 YEARS: the live v2 entry rules (entry_v2.py) and the
live exits (exit_v2.py: smooth arm 0.7 / break 0.6, X1 climax, entry stop) replayed on 1-minute bars
+ the per-minute buy/sell flow history, for every day's 9:30 top-30 list (reports/open_window/bars,
~503 days, Oct 2024 - Oct 2026). Every signal (no slot limit), one position per stock at a time,
re-entry after a loss only above that trade's entry (live rule).
Bar approximations (the live bot polls every 5 s):
  - each minute v2 is evaluated once, at the start of the next minute (forming bar = that minute's open);
    one passing check counts as confirmed (live needs 3 polls ~15 s); buy at that open
  - buy share = the last 15 FINISHED minutes of flow; no quotes -> no spread check
  - exits: stop on the bar's low (filled at the stop or the open if it gapped through); smooth / X1
    decided on finished bars, sold at the next open; 15:55 = that minute's close
Each trade carries the entry features for filter research (extension, VWAP, gap, range, market...).
0.1% cost per trade.   python3 v2_bar_replay.py 2024-10-01..2026-10-02 [out.jsonl]
"""
import gzip
import json
import sys
from datetime import datetime, timezone
from pathlib import Path
from zoneinfo import ZoneInfo

TRADE = Path("/var/www/screener/trade")
sys.path.insert(0, str(TRADE))
import entry_v2
import exit_v2
import reference as REF
from config_loader import get_config

ET = ZoneInfo("America/New_York")
OW = TRADE / "reports" / "open_window"
COST = 0.1
# [2026-10-06] --w-entry: v2 only QUALIFIES the stock; the buy waits for the user's W (1st V support,
# 2nd V proof, first close above the previous bar's high), stop just under the 1st V; same live exits
W_ENTRY = "--w-entry" in sys.argv


def bars_of(rows):
    out = []
    for r in rows:
        t = r[0] if isinstance(r[0], datetime) else datetime.fromtimestamp(r[0], timezone.utc)
        out.append({"t": t, "o": r[1], "h": r[2], "l": r[3], "c": r[4], "v": r[5]})
    return out


def minute(t):
    t = t.astimezone(ET)
    return (t.hour - 9) * 60 + t.minute - 30


def bench_pct(day):
    p = OW / "bars" / f"bench_{day}.json.gz"
    out = {}
    if p.exists():
        d = json.load(gzip.open(p, "rt"))
        for s in ("SPY", "IWM"):
            b = bars_of(d.get(s, []))
            if b:
                o = b[0]["o"]; arr, last = [0.0] * 390, o
                by = {minute(x["t"]): x for x in b}
                for m in range(390):
                    last = by[m]["c"] if m in by else last
                    arr[m] = (last / o - 1) * 100
                out[s] = arr
    return out


def run_stock(day, sym, rows, flow, ref, bench, ecfg, xcfg):
    bars = [b for b in bars_of(rows) if 0 <= minute(b["t"]) < 390]
    if len(bars) < 60:
        return []
    by = {minute(b["t"]): i for i, b in enumerate(bars)}
    trades, pos, pers = [], None, {}
    last_loss = [None]

    def close(t):
        trades.append(t)
        if (t["sell"] / t["buy"] - 1) * 100 - COST <= 0:
            last_loss[0] = t["buy"]
    buy, sell = flow["buy"], flow["sell"]
    qualified, wsig = None, {}
    if W_ENTRY:
        import numpy as np
        from double_bottom_study import signals
        arr = [np.zeros(390) for _ in range(5)]
        last = bars[0]["c"]
        for m_ in range(390):
            b_ = bars[by[m_]] if m_ in by else None
            if b_:
                last = b_["c"]
            for a_, k_ in zip(arr, "ohlcv"):
                a_[m_] = b_[k_] if b_ else (0.0 if k_ == "v" else last)
        # [2026-10-06] the user: only the SAME pattern as RGNX -- 1st V = the day's low (within 0.3%, the 9:30
        # opening wick ignored), a clear >= 2% bounce, the 2nd V holding the 1st V within -0.3%..+0.5%
        for v1, v2, mb, stop in signals(tuple(arr), 2.0, 0.3, 0.5, 330, False):
            lows = arr[2][1:v2 + 1]
            if arr[2][v1] > min(lows[lows > 0]) * 1.003:
                continue
            wsig.setdefault(mb - 1, (v1, stop))      # trigger minute -> (1st V, stop)
    for i in range(len(bars) - 1):
        m = minute(bars[i]["t"]); nb = bars[i + 1]
        if m >= 385:
            break
        forming = {"t": nb["t"], "o": nb["o"], "h": nb["o"], "l": nb["o"], "c": nb["o"], "v": 0.0}
        view = bars[:i + 1] + [forming]
        if pos:
            b = bars[i]
            if minute(b["t"]) >= pos["buy_m"] and b["l"] <= pos["stop"]:
                px = min(pos["stop"], b["o"])
                close({**pos, "sell_m": m, "sell": px, "why": "stop"}); pos = None
                continue
            xd = exit_v2.evaluate(view, pos["p"], pos["xs"], xcfg, ref=ref)
            if xd.should_exit and xd.state != "STOP":
                close({**pos, "sell_m": m + 1, "sell": nb["o"], "why": xd.state}); pos = None
            elif xd.should_exit:            # stop on the forming open (gap through)
                close({**pos, "sell_m": m + 1, "sell": nb["o"], "why": "stop"}); pos = None
            continue
        if m + 1 > 345:
            continue
        price = nb["o"]
        if last_loss[0] is not None and price <= last_loss[0] + 0.01:
            pers = {}
            continue
        lo = max(0, m - 14)
        f15 = (sum(buy[lo:m + 1]), sum(sell[lo:m + 1]))
        d = entry_v2.evaluate(sym, view, ref, f15, pers, as_of=nb["t"], cfg=ecfg, quote=None)
        pers = d.persistence
        if W_ENTRY:
            if d.should_enter and qualified is None:
                qualified = m
            pers = {} if d.should_enter else pers
            if qualified is None or m not in wsig:
                continue
            stop = wsig[m][1]
            if stop >= price:
                continue
            mt = d.metrics
            pos = {"day": day, "sym": sym, "buy_m": m + 1, "buy": price, "stop": stop, "qualified_m": qualified,
                   "feat": {k: mt.get(k) for k in ("ext_open_pct", "move_x", "vwap_pct", "range_pos", "rvol_sofar")},
                   "xs": {}, "p": {"entry_price": price, "stop_price": stop, "entry_time": nb["t"].isoformat()}}
            continue
        if d.should_enter:
            stop = d.metrics.get("stage3", {}).get("stop")
            if not stop or stop >= price:
                continue
            mt = d.metrics
            atrp = ref["atr14"] / ref["prev_close"] * 100 if ref.get("atr14") and ref.get("prev_close") else None
            feat = {k: mt.get(k) for k in ("ext_open_pct", "move_x", "vwap_pct", "range_pos", "rvol_sofar", "vol15_x",
                                          "buy_share15", "r2_15", "eff15", "acc5", "day_high_age_min", "room_day_high_pct")}
            feat.update(breakout=(mt.get("breakout") or {}).get("level"),
                        room=(mt.get("sr14") or {}).get("dist_to_resistance_pct"),
                        above_14d_high=(mt.get("sr14") or {}).get("above_14d_high"),
                        gap_pct=(bars[0]["o"] / ref["prev_close"] - 1) * 100 if ref.get("prev_close") else None,
                        prev_close_atr_x=((price / ref["prev_close"] - 1) * 100 / atrp) if atrp else None,
                        atr_pct=atrp, spy=bench.get("SPY", [0] * 390)[m], iwm=bench.get("IWM", [0] * 390)[m],
                        avoid_hits=mt.get("avoid_hits"),          # [2026-10-12] avoid_rules_test.py
                        flow_net60=((sum(buy[max(0, m - 59):m + 1]) - sum(sell[max(0, m - 59):m + 1]))
                                    / max(sum(buy[max(0, m - 59):m + 1]) + sum(sell[max(0, m - 59):m + 1]), 1)))
            pos = {"day": day, "sym": sym, "buy_m": m + 1, "buy": price, "stop": stop, "feat": feat, "xs": {},
                   "p": {"entry_price": price, "stop_price": stop, "entry_time": nb["t"].isoformat()}}
            pers = {}
    if pos:
        last = bars[min(by.get(385, len(bars) - 1), len(bars) - 1)]
        trades.append({**pos, "sell_m": 385, "sell": last["c"], "why": "15:55"})
    out = []
    for t in trades:
        t.pop("xs", None); t.pop("p", None)
        t["pl"] = (t["sell"] / t["buy"] - 1) * 100 - COST
        out.append(t)
    return out


def main(rng, out_path=None):
    a, b = rng.split("..")
    cfg = get_config()
    ecfg = {**(cfg.get("entry_v2") or {}), "confirm_checks": 1}
    xcfg = {**(cfg.get("exit_v2") or {}), "enabled": True}
    out = open(out_path or (Path(__file__).parent / f"v2_bar_replay_{a}_{b}.jsonl"), "w")
    n = 0
    for p in sorted(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 = bench_pct(day)
        k = 0
        for s in d["top30_current"]:
            fp = OW / "flow" / day / f"{s}.json"
            ref = REF.load(day, s)
            if s not in d["symbols"] or not fp.exists() or not ref:
                continue
            for t in run_stock(day, s, d["symbols"][s]["bars"], json.loads(fp.read_text()), ref, bench, ecfg, xcfg):
                out.write(json.dumps(t, default=str) + "\n"); k += 1
        REF._CACHE.clear()
        n += 1
        print(day, k, "trades", flush=True)
    out.close()


if __name__ == "__main__":
    main(sys.argv[1], sys.argv[2] if len(sys.argv) > 2 else None)
