"""
r8_setup.py -- [2026-10-23] The user's setup R8 "FIRST PULLBACK AFTER A REVERSAL OFF THE LOW" (from the RCAT 10/20/2025
practice chart, ATR 15.2%, gap +6%: a quiet bleed 12.52 -> 11.59 (10:19), reversal with buyers 65-73% to 11.84 (10:30), a
QUIET pullback (0.2-0.5x volume, buyers ~50%) to 11.66 = a higher low, 10:40 turn bar with 78% buyers -> buy 10:41 open
11.705, +2% at 10:54; the user's mark "~11.70 after the reversal on the small pullback").
  1 SELL-OFF   the day low L is >= max(drop_pct 3%, drop_atr 0.25 x ATR %) under the day high before it
  2 REVERSAL   within leg_max (20) bars after L a high RH >= max(leg_pct 1%, leg_atr 0.1 x ATR %) above L, buyers >= leg_bs
               (55%) on the reversal bars
  3 PULLBACK   from RH a pullback to PL above L (higher low), retracing <= pb_max (80%) of the reversal; QUIET: mean volume of
               the pullback bars <= the reversal bars' and buyers >= pb_bs (40%)
  4 TURN       the trigger bar closes above the bar before, buyers >= turn_bs (60%), gain >= turn_gain (0.15%) from its open
  5 ROOM       VWAP >= room_pct (1.5%) above the close
  safety       >= min_spm shares/min; 9:45-13:00; cool-down 30 min
When R8 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": 3.0, "drop_atr": 0.25, "leg_max": 20, "leg_pct": 1.0, "leg_atr": 0.1, "leg_bs": 0.55,
            "pb_max": 0.80, "pb_bs": 0.40, "turn_bs": 0.60, "turn_gain": 0.15, "room_pct": 1.5, "min_spm": 2000,
            "first_m": 15, "last_m": 210, "cooldown": 30}


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 < 15:
        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]
    bsj = lambda js: (sum(fb[mins[j]] for j in js) / max(sum(fb[mins[j]] + fs[mins[j]] for j in js), 1e-9)) if js else 0.0
    jl = min(range(n - 1), key=lambda j: done[j]["l"])
    L = done[jl]["l"]
    if jl < 3:
        return False, {"why_not": "1 low at the open"}
    Hd = max(x["h"] for x in done[:jl + 1])
    drop = (Hd / L - 1) * 100
    if drop < max(c["drop_pct"], c["drop_atr"] * atrp):
        return False, {"why_not": f"1 sell-off {drop:.1f}% too small"}
    leg = [j for j in range(jl + 1, min(jl + 1 + c["leg_max"], n - 1))]
    if len(leg) < 2:
        return False, {"why_not": "2 no reversal yet"}
    jr = max(leg, key=lambda j: done[j]["h"])
    RH = done[jr]["h"]
    if (RH / L - 1) * 100 < max(c["leg_pct"], c["leg_atr"] * atrp):
        return False, {"why_not": f"2 reversal {(RH / L - 1) * 100:.1f}% too small"}
    up = list(range(jl + 1, jr + 1))
    if bsj(up) < c["leg_bs"]:
        return False, {"why_not": f"2 reversal without buyers ({bsj(up):.0%})"}
    pb = list(range(jr + 1, n - 1))
    if not pb:
        return False, {"why_not": "3 no pullback yet"}
    PL = min(min(done[j]["l"] for j in pb), done[-1]["l"])
    if PL <= L or (RH - PL) > c["pb_max"] * (RH - L):
        return False, {"why_not": f"3 pullback too deep ({(RH - PL) / (RH - L):.0%})"}
    if sum(done[j]["v"] for j in pb) / len(pb) > sum(done[j]["v"] for j in up) / len(up):
        return False, {"why_not": "3 pullback not quiet"}
    if bsj(pb) < c["pb_bs"]:
        return False, {"why_not": f"3 sellers on the pullback ({bsj(pb):.0%})"}
    P = done[-1]["c"]; t_ = fb[m] + fs[m]
    if P <= done[-2]["c"] or not t_ or fb[m] / t_ < c["turn_bs"] or (P / done[-1]["o"] - 1) * 100 < c["turn_gain"]:
        return False, {"why_not": "4 no turn bar"}
    pv = sum((x["h"] + x["l"] + x["c"]) / 3 * x["v"] for x in done); cv = sum(x["v"] for x in done)
    vwap = pv / cv if cv else P
    room = (vwap / P - 1) * 100
    if room < c["room_pct"]:
        return False, {"why_not": f"5 room to VWAP {room:.1f}%"}
    if sum(x["v"] for x in done[-5:]) / 5 < c["min_spm"]:
        return False, {"why_not": "thin"}
    return True, {"support": PL, "support_m": mins[jl], "day_low": L, "reversal_high": RH, "drop": round(drop, 1),
                  "retrace": round((RH - PL) / (RH - L), 2), "room": round(room, 2)}
