"""
r1e_setup.py -- [2026-10-23] The user's setup R1E "SELLING EXHAUSTION AT THE LOW" (from RKT 2/28/2025, sample chart #14: gapped
up 10% to 14.11, then BLED lower -- no flush: 10 bars on light volume (0.4-0.9x the day's median) while the 15-min buy share ROSE
33% -> 47%; 9:46 made the day's low 13.36 (-5.3%, 1.2x the daily ATR, far above the previous day's low 12.77 / close 12.83) and
closed off it; the user's buy = right there; 9:47 sold 2x volume at 18% buyers and could NOT make a new low; 14.08 by 10:02).
Not a spring (R1D: the low bar had 14% buyers, no reclaim, no volume) and not a turn bar (R1C) -- the sellers just run out.
  1 NEW LOW    the trigger bar makes the day's new low and closes off it (close position in its range >= close_pos 0.4)
  2 USED UP    the open -> low drop >= drop_atr (1.0) x the daily ATR
  3 BLEED      no flush: every one of the last bleed_n (10) bars < bleed_x (1.5) x the day's median minute volume (the busy
               opening minutes lift the median: RKT 9:38 = 1.31x; CERT's 9:42 flush = 3.25x)
  4 DIVERGENCE the price fell over those bars (close < the close bleed_n bars before) while the 15-min buy share ROSE by
               >= div_up (8 points) to >= bs15_min (45%, the N3 level)
  5 SUPPORT    the low is above the previous day's low (a QBTS-type breakdown under it is out)
  safety       >= min_spm shares/min over 5 bars; 9:40-14:30; one trigger per low (cool-down)
STOP = under the low (info "support"). Untested on 2 years. Pure function, no orders.
"""
DEFAULTS = {"close_pos": 0.4, "drop_atr": 1.0, "bleed_n": 10, "bleed_x": 1.5, "div_up": 0.08, "bs15_min": 0.45,
            "min_spm": 2000, "first_m": 10, "last_m": 300, "cooldown": 20}


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, k = len(done), c["bleed_n"]
    if m < c["first_m"] or m >= c["last_m"] or n < k + 2 or not ref.get("atr14"):
        return False, {}
    b = done[-1]
    # 1 new low, closed off it
    if b["l"] >= min(x["l"] for x in done[:-1]):
        return False, {"why_not": "1 no new low"}
    pos = (b["c"] - b["l"]) / (b["h"] - b["l"]) if b["h"] > b["l"] else 0
    if pos < c["close_pos"]:
        return False, {"why_not": f"1 closed at the low (position {pos:.2f})"}
    # 2 used up
    drop = done[0]["o"] - b["l"]
    if drop < c["drop_atr"] * ref["atr14"]:
        return False, {"why_not": f"2 drop {drop / ref['atr14']:.2f}x ATR"}
    # 5 support
    if ref.get("prev_low") and b["l"] <= ref["prev_low"]:
        return False, {"why_not": f"5 under the previous day's low {ref['prev_low']}"}
    # 3 bleed, no flush
    vs = sorted(x["v"] for x in done[:-1]); med = vs[len(vs) // 2]
    big = max(x["v"] for x in done[-k:])
    if not med or big > c["bleed_x"] * med:
        return False, {"why_not": f"3 a heavy bar in the last {k} ({big / med if med else 0:.2f}x median) -- a flush, not a bleed"}
    # 4 divergence
    fb, fs = flow["buy"], flow["sell"]
    def bs15(mm):
        B = sum(fb[max(0, mm - 14):mm + 1]); S = sum(fs[max(0, mm - 14):mm + 1]); return B / (B + S) if B + S else 0.5
    a = done[-1 - k]
    s_now, s_then = bs15(m), bs15(_minute(a["t"]))
    if not (b["c"] < a["c"] and s_now - s_then >= c["div_up"] and s_now >= c["bs15_min"]):
        return False, {"why_not": f"4 no divergence: price {a['c']} -> {b['c']}, 15-min buyers {s_then:.0%} -> {s_now:.0%}"}
    if sum(x["v"] for x in done[-5:]) / 5 < c["min_spm"]:
        return False, {"why_not": "thin"}
    return True, {"support": b["l"], "support_m": m, "drop_atr": round(drop / ref["atr14"], 2), "bleed_max_x": round(big / med, 2),
                  "bs15_then": round(s_then, 3), "bs15": round(s_now, 3), "close_pos": round(pos, 2)}
