"""
r9_setup.py -- [2026-10-23] The user's setup R9 "BUY THE STOP 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 STOP       the trigger bar makes no new low (its low >= the bar before's low) and the last 3 lows lie within stop_pct (0.3%)
  4 FADING     the trigger bar's volume <= fade (50%) of the biggest climax bar, buyers >= turn_bs (50%), close >= its open
  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, "stop_pct": 0.3, "fade": 0.50, "turn_bs": 0.50, "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"}
    # 2 climax bars (before the trigger bar)
    cl = []
    for j in range(n - 1 - c["climax_bars"], n - 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"}
    # 3 stop
    lows = [x["l"] for x in done[-3:]]
    if done[-1]["l"] < done[-2]["l"] or (max(lows) / min(lows) - 1) * 100 > c["stop_pct"]:
        return False, {"why_not": "3 still falling"}
    if min(lows) > lowest * 1.003:
        return False, {"why_not": "3 not at the low"}
    # 4 fading
    t_ = fb[m] + fs[m]
    big = max(done[j]["v"] for j in cl)
    if done[-1]["v"] > c["fade"] * big or not t_ or fb[m] / t_ < c["turn_bs"] or P < done[-1]["o"]:
        return False, {"why_not": "4 selling not fading"}
    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[min(range(n), key=lambda j: done[j]["l"] if j >= n - c["high_bars"] else 1e18)],
                  "high": H, "drop": round(drop, 2), "climax_bars": len(cl), "fade": round(done[-1]["v"] / big, 2), "room": round(room, 2)}
