"""
r10_setup.py -- [2026-10-25] The user's setup R10 "GAP-DOWN RECOVERY RECLAIMS VWAP" (from the Star bot's live winners 10/5-10/23
that EV3 missed: CORZ +6.0% 10/15, DNA +3.5% 10/7, AVO +3.3%, RIOT +2.6%, UUUU +2.4%, PUMP +1.9%, BKKT, NAVI, MUX, QXO, BLMN,
QUBT: gapped down or fell after the open, then climbed back ABOVE VWAP with buyers; most 10:00-11:00).
  1 DOWN FIRST   the open gapped down >= gap_min (1%) under the previous close, OR the day's low so far is >= drop_min (2%)
                 under the open
  2 RECLAIM      the close is 0.3%..reclaim_max (1.5%) over the session VWAP, and fresh: a close under VWAP within the last
                 fresh_n (10) bars
  3 CLIMBING     up >= ch15_min (1%) over the last 15 bars
  4 BUYERS       15-min buy share >= bs15_min (50%)
  5 VOLUME       RVOL so far >= rvol_min (1.5x the 14-day volume by minute)
  safety         9:50-11:30 (first_m 20, last_m 120); >= min_spm shares/min over 5 bars; one trigger per reclaim (cool-down)
STOP = the lowest low of the last stop_n (15) bars (clamped 0.5-4% by EV3). Note: R10 buys gap-downs on purpose -- the A20 gate must
not be applied to it. Untested on 2 years when written. Pure function, no orders.
"""
DEFAULTS = {"gap_min": 1.0, "drop_min": 2.0, "reclaim_min": 0.3, "reclaim_max": 1.5, "fresh_n": 10, "ch15_min": 1.0,
            "bs15_min": 0.50, "rvol_min": 1.5, "first_m": 20, "last_m": 120, "min_spm": 2000, "stop_n": 15, "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 < 16 or not ref.get("prev_close"):
        return False, {}
    O = done[0]["o"]; P = done[-1]["c"]
    gap = (O / ref["prev_close"] - 1) * 100; lo = min(x["l"] for x in done)
    if not (gap <= -c["gap_min"] or (lo / O - 1) * 100 <= -c["drop_min"]):
        return False, {"why_not": f"1 not down first (gap {gap:+.1f}%, low {(lo / O - 1) * 100:+.1f}% under the open)"}
    pv = cv = 0.0; vw = []
    for x in done:
        pv += (x["h"] + x["l"] + x["c"]) / 3 * x["v"]; cv += x["v"]; vw.append(pv / cv if cv else x["c"])
    over = (P / vw[-1] - 1) * 100
    if not (c["reclaim_min"] <= over <= c["reclaim_max"]):
        return False, {"why_not": f"2 {over:+.2f}% vs VWAP"}
    if not any(done[i]["c"] < vw[i] for i in range(max(0, n - 1 - c["fresh_n"]), n - 1)):
        return False, {"why_not": "2 not a fresh reclaim"}
    ch = (P / done[-16]["c"] - 1) * 100
    if ch < c["ch15_min"]:
        return False, {"why_not": f"3 15-bar change {ch:+.2f}%"}
    fb, fs = flow["buy"], flow["sell"]
    B = sum(fb[max(0, m - 14):m + 1]); S = sum(fs[max(0, m - 14):m + 1])
    bs15 = B / (B + S) if B + S else 0
    if bs15 < c["bs15_min"]:
        return False, {"why_not": f"4 15-min buy share {bs15:.0%}"}
    vpm = ref.get("vol_per_min") or []
    norm = sum(vpm[:m + 1]) if len(vpm) > m else 0
    rv = cv / norm if norm else None
    if rv is not None and rv < c["rvol_min"]:
        return False, {"why_not": f"5 RVOL {rv:.2f}x"}
    if sum(x["v"] for x in done[-5:]) / 5 < c["min_spm"]:
        return False, {"why_not": "thin"}
    sup = min(x["l"] for x in done[-c["stop_n"]:])
    return True, {"support": sup, "support_m": _minute(done[-c["stop_n"]]["t"]), "gap": round(gap, 2), "vs_vwap": round(over, 2),
                  "ch15": round(ch, 2), "bs15": round(bs15, 3), "rvol": round(rv, 2) if rv else None}
