"""
r9_setup.py -- [2026-10-23, v2 the user: "buy after the reversal around 10:00", not at the stop] R9 "REVERSAL AFTER A SELLING CLIMAX" (from the SOUN 3/27/2026 practice chart,
ATR 7.8%: a drift up to 6.07 (9:48), then a sharp sell-off 6.07 -> 5.86 with four heavy selling bars 9:52-9:57 (1.6-4.0x
volume, 26-38% buyers); the fall stopped (lows 5.88 / 5.87 / 5.86 / 5.86), 9:58 traded a third of the biggest climax bar with
buyers back to 50% -> buy 9:59 open ~5.88, +2% around 10:51; the user's entry "9:55-9:58"). The EARLIEST entry of all the
setups: no base, no bounce, no retest -- so it needs the climax AND the stop.
  1 SELL-OFF   from the high of the last high_bars (20) bars down >= max(drop_pct 2%, drop_atr 0.3 x ATR %)
  2 CLIMAX     >= climax_n (3) of the last climax_bars (6) bars with >= climax_vol_x (1.5x) normal volume and <= climax_bs
               (40%) buyers
  3 STOPPED    the day's low of the sell-off was made within rev_max (8) bars before the trigger and no bar since went under it
  4 REVERSAL   the trigger bar closes above the highs of the rev_bars (3) bars before it, with buyers >= turn_bs (55%) and
               volume <= fade (50%) of the biggest climax bar (no new selling wave)
  5 ROOM       the sell-off's high >= room_pct (2%) above the close
  safety       >= min_spm shares/min; 9:45-14:30; cool-down 30 min
When R9 is true these v2 rules do NOT apply: RVOL, 15-min buy share / steady trend, price >= VWAP, below the open.
Our earlier V-turn tests (10/10) lost on average -- R9 is the riskiest setup; the 2-year test decides. Pure function.
"""
DEFAULTS = {"high_bars": 20, "drop_pct": 2.0, "drop_atr": 0.3, "climax_n": 3, "climax_bars": 6, "climax_vol_x": 1.5,
            "climax_bs": 0.40, "rev_max": 8, "rev_bars": 3, "fade": 0.50, "turn_bs": 0.55, "room_pct": 2.0, "min_spm": 2000,
            "first_m": 15, "last_m": 300, "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 < c["high_bars"]:
        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"]
    vpm = ref.get("vol_per_min") or []
    mins = [_minute(b["t"]) for b in done]
    H = max(x["h"] for x in done[-c["high_bars"]:])
    P = done[-1]["c"]
    lowest = min(x["l"] for x in done[-c["high_bars"]:])
    drop = (H / lowest - 1) * 100
    if drop < max(c["drop_pct"], c["drop_atr"] * atrp):
        return False, {"why_not": f"1 sell-off {drop:.1f}% too small"}
    # 3 the low of the sell-off, recent, not broken since
    jl = min(range(n - c["high_bars"], n), key=lambda j: done[j]["l"])
    if n - 1 - jl > c["rev_max"] or jl == n - 1:
        return False, {"why_not": "3 the low is not recent / still falling"}
    # 2 climax bars around the low (the bars before the low and the low bar)
    cl = []
    for j in range(max(0, jl - c["climax_bars"] + 1), jl + 1):
        k = mins[j]; t_ = fb[k] + fs[k]
        if k < len(vpm) and vpm[k] and done[j]["v"] >= c["climax_vol_x"] * vpm[k] and t_ and fb[k] / t_ <= c["climax_bs"]:
            cl.append(j)
    if len(cl) < c["climax_n"]:
        return False, {"why_not": f"2 only {len(cl)} climax bars"}
    # 4 reversal bar
    t_ = fb[m] + fs[m]
    big = max(done[j]["v"] for j in cl)
    if P <= max(x["h"] for x in done[-1 - c["rev_bars"]:-1]):
        return False, {"why_not": "4 no reversal close"}
    if not t_ or fb[m] / t_ < c["turn_bs"] or done[-1]["v"] > c["fade"] * big:
        return False, {"why_not": "4 reversal without buyers / new selling wave"}
    room = (H / P - 1) * 100
    if room < c["room_pct"]:
        return False, {"why_not": f"5 room {room:.1f}%"}
    if sum(x["v"] for x in done[-5:]) / 5 < c["min_spm"]:
        return False, {"why_not": "thin"}
    return True, {"support": lowest, "support_m": mins[jl],
                  "high": H, "drop": round(drop, 2), "climax_bars": len(cl), "bars_after_low": n - 1 - jl, "room": round(room, 2)}
