"""
r6_setup.py -- [2026-10-23] The user's setup R6 "STAIRCASE OUT OF A LONG BASE, TOWARD VWAP" (from the FRMI 7/30/2026
practice chart, ATR 12.1%: morning drive to 6.67, pullback, a 4-hour base 6.24-6.44 under VWAP, then from ~12:50 rising
10-minute lows 6.25 -> 6.29 -> 6.32 -> 6.34 on quiet volume with buyers 59-64% over 30 min, price back up to -0.5% under
VWAP; the user's entry ~13:30 -> buy 13:31 open 6.365, +2% at 14:14, low after 6.35, afternoon high 6.76).
  1 LONG BASE  the base_min (60) minutes before the staircase stay inside <= base_atr (0.3) x daily ATR %
  2 STAIRCASE  the lows of the last steps (3) blocks of step_m (10) minutes each are each higher than the block before
  3 BUYERS     buy share over the last 30 minutes >= bs30 (55%)
  4 NEAR VWAP  price under or at VWAP by no more than vwap_max (1%), and not above it by more than vwap_over (0.5%)
  5 ROOM       today's high so far >= room_pct (2%) above the close
  6 TURN       the trigger bar closes >= the bar before with buyers >= turn_bs (50%)
  safety       >= min_spm shares/min over 15 min; 10:30-14:30; one trigger per staircase (cool-down)
When R6 is true these v2 rules do NOT apply: RVOL, 15-min steady trend, price >= VWAP. Untested on 2 years. Pure function.
"""
DEFAULTS = {"base_min": 60, "base_atr": 0.3, "steps": 3, "step_m": 10, "bs30": 0.55, "vwap_max": 1.0, "vwap_over": 0.5,
            "room_pct": 2.0, "turn_bs": 0.50, "min_spm": 2000, "first_m": 60, "last_m": 300, "cooldown": 60}


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 < 60:
        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]
    stair_start = m - c["steps"] * c["step_m"] + 1
    # 2 staircase: rising lows block by block
    blocks = []
    for k in range(c["steps"] + 1):                       # one block before the staircase as the reference
        a = stair_start - (1 - k) * c["step_m"] if k == 0 else stair_start + (k - 1) * c["step_m"]
        lo_ = [done[j]["l"] for j in range(n) if a <= mins[j] < a + c["step_m"]]
        if not lo_:
            return False, {"why_not": "2 gap in the bars"}
        blocks.append(min(lo_))
    if not all(blocks[k] > blocks[k - 1] for k in range(1, len(blocks))):
        return False, {"why_not": "2 no staircase: " + " -> ".join(f"{x:.2f}" for x in blocks)}
    # 1 long base before the staircase (it may include the first reference block)
    base = [done[j] for j in range(n) if stair_start - c["base_min"] <= mins[j] < stair_start]
    if len(base) < c["base_min"] * 0.7:
        return False, {"why_not": "1 base too short"}
    blo, bhi = min(x["l"] for x in base), max(x["h"] for x in base)
    if (bhi / blo - 1) * 100 > c["base_atr"] * atrp:
        return False, {"why_not": f"1 no long base (range {(bhi / blo - 1) * 100:.1f}% > {c['base_atr'] * atrp:.1f}%)"}
    # 3 buyers over 30 min
    B, S = sum(fb[max(0, m - 29):m + 1]), sum(fs[max(0, m - 29):m + 1])
    if not B + S or B / (B + S) < c["bs30"]:
        return False, {"why_not": f"3 buyers 30 min {B / max(B + S, 1):.0%}"}
    P = done[-1]["c"]
    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
    vd = (P / vwap - 1) * 100
    if vd < -c["vwap_max"] or vd > c["vwap_over"]:
        return False, {"why_not": f"4 VWAP {vd:+.1f}%"}
    dayhi = max(x["h"] for x in done)
    room = (dayhi / P - 1) * 100
    if room < c["room_pct"]:
        return False, {"why_not": f"5 room {room:.1f}%"}
    t_ = fb[m] + fs[m]
    if done[-1]["c"] < done[-2]["c"] or not t_ or fb[m] / t_ < c["turn_bs"]:
        return False, {"why_not": "6 no turn bar"}
    if sum(x["v"] for x in done[-15:]) / 15 < c["min_spm"]:
        return False, {"why_not": "thin"}
    return True, {"support": blo, "support_m": stair_start - c["base_min"], "steps": [round(x, 4) for x in blocks],
                  "buyers30": round(B / (B + S), 2), "vwap_pct": round(vd, 2), "room": round(room, 2)}
