"""
r5_setup.py -- [2026-10-22] The user's setup R5 "OPENING SELL-OFF -> ONE LOW -> BASE -> BREAKOUT" (from the BBAI 9/15/2025
practice chart, ATR 5.3%, very liquid: opening pop to 5.26, sell-off to 5.05 at 9:41 with a heavy selling bar at 9:38
(4.6x volume, 27% buyers), a tight base 5.05-5.12 at the low 9:42-9:47 with buyers back to 50-69%, the user's entry
"right after the base": the 9:48 bar closed 5.14 above the base high -> buy 9:49 open ~5.13 -> +2% at 9:58, high 5.33).
Unlike R1 / R1A there is NO retest -- one low, then a base AT that low.
  1 SELL-OFF   from the high of the first 15 minutes down to the low: >= max(drop_pct 2%, drop_atr 0.3 x daily ATR %)
  2 CAPITULATION  a selling bar within cap_bars (8) bars before / at the low: >= cap_vol_x (2x) normal volume and
               <= cap_bs (35%) buyers
  3 BASE       >= base_min (5) bars since the low, all holding the low (no new low), range <= base_atr (0.3) x ATR %
  4 BUYERS     buy share over the base bars >= base_bs (50%)
  5 BREAKOUT   the trigger bar closes above the base high with buyers >= brk_bs (50%) -> buy the next open
  6 ROOM       the early high (first 15 min) or the open >= room_pct (2%) above the close
  safety       >= min_spm shares/min; 9:40-11:00 (an OPENING sell-off); one trigger per day
When R5 is true these v2 rules do NOT apply: RVOL, 15-min buy share / steady trend, price >= VWAP, below the open.
Untested on 2 years. Pure function, no orders.
"""
DEFAULTS = {"drop_pct": 2.0, "drop_atr": 0.3, "cap_bars": 8, "cap_vol_x": 2.0, "cap_bs": 0.35, "base_min": 5,
            "base_atr": 0.3, "base_bs": 0.50, "brk_bs": 0.50, "room_pct": 2.0, "min_spm": 2000, "first_m": 10,
            "last_m": 90, "cooldown": 999}


def _minute(t):
    from datetime import datetime, timezone
    from zoneinfo import ZoneInfo
    if not isinstance(t, datetime):
        t = datetime.fromtimestamp(t, timezone.utc)
    t = t.astimezone(ZoneInfo("America/New_York"))
    return (t.hour - 9) * 60 + t.minute - 30


def check(done, flow, ref, m, c=None):
    c = {**DEFAULTS, **(c or {})}
    ref = ref or {}
    n = len(done)
    if m < c["first_m"] or m > c["last_m"] or n < 10:
        return False, {}
    atrp = ref["atr14"] / ref["prev_close"] * 100 if ref.get("atr14") and ref.get("prev_close") else None
    if not atrp:
        return False, {}
    fb, fs = flow["buy"], flow["sell"]
    mins = [_minute(b["t"]) for b in done]
    vpm = ref.get("vol_per_min") or []
    # the low of the day so far (before the trigger bar) and the early high before it
    jl = min(range(n - 1), key=lambda j: done[j]["l"])
    L = done[jl]["l"]
    early = [j for j in range(jl + 1) if mins[j] < 15]
    if not early:
        return False, {}
    jh = max(early, key=lambda j: done[j]["h"])
    H = done[jh]["h"]
    drop = (H / L - 1) * 100
    need = max(c["drop_pct"], c["drop_atr"] * atrp)
    if drop < need:
        return False, {"why_not": f"1 sell-off {drop:.1f}% < {need:.1f}%"}
    # 2 capitulation bar near the low
    cap = None
    for j in range(max(jh, jl - c["cap_bars"]), jl + 1):
        k = mins[j]; t_ = fb[k] + fs[k]
        if k < len(vpm) and vpm[k] and done[j]["v"] >= c["cap_vol_x"] * vpm[k] and t_ and fb[k] / t_ <= c["cap_bs"]:
            cap = j
    if cap is None:
        return False, {"why_not": "2 no capitulation bar"}
    # 3 base at the low (bars after the low, before the trigger bar)
    base = done[jl + 1:n - 1]
    if len(base) < c["base_min"]:
        return False, {"why_not": "3 base too short"}
    bhi = max(x["h"] for x in base); blo = min(x["l"] for x in base)
    if blo < L or (bhi / L - 1) * 100 > c["base_atr"] * atrp:
        return False, {"why_not": f"3 no base at the low (range {(bhi / L - 1) * 100:.2f}%)"}
    # 4 buyers in the base
    ks = [mins[j] for j in range(jl + 1, n - 1)]
    B, S = sum(fb[k] for k in ks), sum(fs[k] for k in ks)
    if not B + S or B / (B + S) < c["base_bs"]:
        return False, {"why_not": f"4 base buyers {B / max(B + S, 1):.0%}"}
    # 5 breakout
    P = done[-1]["c"]; t_ = fb[m] + fs[m]
    if P <= bhi or not t_ or fb[m] / t_ < c["brk_bs"]:
        return False, {"why_not": "5 no breakout"}
    room = (max(H, done[0]["o"]) / P - 1) * 100
    if room < c["room_pct"]:
        return False, {"why_not": f"6 room {room:.1f}%"}
    if sum(x["v"] for x in done[-5:]) / 5 < c["min_spm"]:
        return False, {"why_not": "thin"}
    return True, {"support": L, "support_m": mins[jl], "early_high": H, "drop": round(drop, 2), "capitulation_m": mins[cap],
                  "base_hi": bhi, "base_bs": round(B / (B + S), 2), "room": round(room, 2)}
