"""
r1b_setup.py -- [2026-10-23] The user's setup R1B "UNDERCUT AND RECLAIM AFTER A FLUSH (deep V / spring)" (from PEPG 10/1/2025:
10:02 flush to 4.67 on 4.4x volume with 28% buyers, bounce to ~4.79, a second push 10:06-10:09 that UNDERCUT the flush low to
4.63 (10:08: 5% buyers), then the reclaim -- 10:09 85% buyers, 10:10 +2.4% in one bar with 68% buyers -- and a quiet hold
4.75-4.80 (10:11-10:16). The user's entry ~10:15 at ~4.775; the trade lives on the V LOW (4.63): its stop belongs under it
(~3% here), so the 10:40 dip to 4.695 does not shake it out, and it reached 4.918 (+3%) at 11:14.
A version of R1A (fast double bottom) for a retest that BREAKS the flush low a little and snaps back.
  1 FLUSH      a bar within flush_window (20) bars: >= flush_vol_x (3x) normal volume, >= flush_sell (60%) sellers, a new day low
  2 BOUNCE     after the flush low a bounce >= max(bounce_pct 1%, bounce_atr 0.15 x daily ATR %)
  3 UNDERCUT   a second push below the flush low by no more than max(under_pct 1.5%, under_atr 0.25 x ATR %) -- the V low
  4 RECLAIM    within reclaim_max (4) bars of the V low: a bar closing back ABOVE the flush low, gaining >= max(rec_pct 1.5%,
               rec_atr 0.15 x ATR %) from its open, with buyers >= rec_bs (60%)
  5 HOLD       hold_min..hold_max (2..6) bars after the reclaim bar staying within hold_pct (1.2%) of the reclaim high and never
               back under the flush low, on volume <= the reclaim bar's -> buy on the bar that completes the hold
  6 ROOM       VWAP or the open >= room_pct (2%) above
  STOP         under the V low (info "stop" = V low x 0.998) -- not a fixed %
  safety       >= min_spm shares/min; 9:45-14:30; one trigger per V (cool-down)
When R1B is true these v2 rules do NOT apply: RVOL, 15-min buy share / steady trend, price >= VWAP, below the open.
NOT run yet (the user: build only). Pure function, no orders.
"""
DEFAULTS = {"flush_window": 20, "flush_vol_x": 3.0, "flush_sell": 0.60, "bounce_pct": 1.0, "bounce_atr": 0.15,
            "under_pct": 1.5, "under_atr": 0.25, "reclaim_max": 4, "rec_pct": 1.5, "rec_atr": 0.15, "rec_bs": 0.60,
            "hold_min": 2, "hold_max": 6, "hold_pct": 1.2, "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 < 12:
        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]
    bs = lambda j: fb[mins[j]] / (fb[mins[j]] + fs[mins[j]]) if fb[mins[j]] + fs[mins[j]] else 0.5
    # 3 the V low = the lowest low so far (must be recent) ; 1 the flush = the last heavy selling bar BEFORE it that made a new low
    jv = min(range(n), key=lambda j: done[j]["l"])
    V = done[jv]["l"]
    if n - 1 - jv > c["reclaim_max"] + c["hold_max"] or jv < 3:
        return False, {"why_not": "3 no recent V low"}
    jf = None
    for j in range(max(1, jv - c["flush_window"]), jv):
        k = mins[j]
        if (k < len(vpm) and vpm[k] and done[j]["v"] >= c["flush_vol_x"] * vpm[k] and 1 - bs(j) >= c["flush_sell"]
                and done[j]["l"] <= min(x["l"] for x in done[:j]) * 1.0005):
            jf = j
    if jf is None:
        return False, {"why_not": "1 no flush before the V"}
    F = min(done[j]["l"] for j in range(jf, min(jf + 2, jv)))
    under = (F / V - 1) * 100
    if under <= 0 or under > max(c["under_pct"], c["under_atr"] * atrp):
        return False, {"why_not": f"3 undercut {under:.2f}% (needs 0..{max(c['under_pct'], c['under_atr'] * atrp):.2f}%)"}
    # 2 bounce between the flush and the V
    mid = range(jf + 1, jv)
    if not mid or (max(done[j]["h"] for j in mid) / F - 1) * 100 < max(c["bounce_pct"], c["bounce_atr"] * atrp):
        return False, {"why_not": "2 no bounce between the flush and the V"}
    # 4 reclaim bar
    jr = None
    for j in range(jv, min(jv + c["reclaim_max"] + 1, n)):
        b = done[j]
        if b["c"] > F and (b["c"] / b["o"] - 1) * 100 >= max(c["rec_pct"], c["rec_atr"] * atrp) and bs(j) >= c["rec_bs"]:
            jr = j; break
    if jr is None:
        return False, {"why_not": "4 no reclaim bar"}
    # 5 hold after the reclaim (the trigger = the bar that completes it)
    hold = list(range(jr + 1, n))
    if not (c["hold_min"] <= len(hold) <= c["hold_max"]):
        return False, {"why_not": f"5 hold {len(hold)} bars"}
    RH = max(done[j]["h"] for j in range(jr, n))
    if any(done[j]["l"] < F for j in hold) or any((RH / done[j]["c"] - 1) * 100 > c["hold_pct"] for j in hold) \
            or any(done[j]["v"] > done[jr]["v"] for j in hold):
        return False, {"why_not": "5 the hold did not hold"}
    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
    room = (max(vwap, done[0]["o"]) / P - 1) * 100
    if room < c["room_pct"]:
        return False, {"why_not": f"6 room {room:.1f}%"}
    if sum(x["v"] for x in done[-5:]) / 5 < c["min_spm"]:
        return False, {"why_not": "thin"}
    return True, {"support": V, "support_m": mins[jv], "stop": round(V * 0.998, 4), "flush_low": F, "flush_m": mins[jf],
                  "undercut": round(under, 2), "reclaim_m": mins[jr], "room": round(room, 2)}
