"""
r1a_setup.py -- [2026-10-22] The user's setup R1A "FAST DOUBLE BOTTOM AFTER A FLUSH" -- a version of R1 for the quick retest
(from the HELP 7/3/2025 practice chart: gap +7.7%, ATR 9.5%; 9:48-9:49 flush on 14.4x / 12.6x volume to 7.55, bounce to
7.69-7.73, sellers back, retest of 7.55 at 9:53-9:54 on far less volume, then the recovery to 7.90 by 10:10; "+2% before
-1%" zone 9:53-10:07). R1 missed it: its support must be 10+ bars old and its bounce >= 1/4 ATR.
  1 FLUSH      a bar in the last flush_window (15) bars with >= flush_vol_x (3x) normal volume, sellers >= flush_sell
               (60%), that made the day's low so far (the flush low)
  2 BOUNCE     after the flush low, a bounce >= max(bounce_pct 1%, bounce_atr 0.15 x daily ATR %)
  3 RETEST     within retest_max (10) bars of the flush, a low back within near_pct (0.4%) of the flush low, not broken by
               more than break_pct (0.3%)
  4 WEAKER     volume of the retest bars <= retest_vol (0.5) x the flush bar's volume (the sellers are spent)
  5 TURN       the trigger bar (the retest bar or a bar after it) closes above the bar before with buyers >= turn_bs (55%)
  6 ROOM       the higher of VWAP and the open >= room_pct (2%) above the close
  safety       >= min_spm shares/min over 5 bars; <= max_under_vwap (4%) under VWAP (a flush pushes the price under it);
               9:40-14:30; one trigger per flush
When R1A is true these v2 rules do NOT apply: RVOL, 15-min buy share / steady trend, price >= VWAP, below the open.
Untested on 2 years. Pure function, no orders.
"""
DEFAULTS = {"flush_window": 15, "flush_vol_x": 3.0, "flush_sell": 0.60, "bounce_pct": 1.0, "bounce_atr": 0.15,
            "retest_max": 10, "near_pct": 0.4, "break_pct": 0.3, "retest_vol": 0.5, "turn_bs": 0.55, "room_pct": 2.0,
            "min_spm": 2000, "max_under_vwap": 4.0, "first_m": 10, "last_m": 300, "cooldown": 20}


def _minute(t):
    """minutes since 9:30 ET of a bar time (datetime or epoch seconds) -- [2026-10-22] flow is looked up by the bar's own
    minute, not its position (thin stocks have minutes without a bar)"""
    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 < 8:
        return False, {}
    fb, fs = flow["buy"], flow["sell"]
    vpm = ref.get("vol_per_min") or []
    m0 = m - (n - 1)
    norm = lambda k: vpm[min(max(k, 0), len(vpm) - 1)] if vpm else 0
    atrp = ref["atr14"] / ref["prev_close"] * 100 if ref.get("atr14") and ref.get("prev_close") else 0.0
    # 1 flush: heavy selling bar that made the day low so far
    fj = None
    for j in range(max(1, n - 1 - c["flush_window"]), n - 1):
        b = done[j]; k = _minute(b["t"]); t_ = fb[k] + fs[k]
        if (norm(k) and b["v"] >= c["flush_vol_x"] * norm(k) and t_ and fs[k] / t_ >= c["flush_sell"]
                and b["l"] <= min(x["l"] for x in done[:j]) * 1.0005):
            fj = j
    if fj is None:
        return False, {"why_not": "1 no flush"}
    # the flush low = lowest low of the flush bar and the next bar
    lj = min(range(fj, min(fj + 2, n - 1)), key=lambda j: done[j]["l"])
    L = done[lj]["l"]
    after = done[lj + 1:]
    if len(after) < 2:
        return False, {"why_not": "2 no bounce yet"}
    # 3 retest: the lowest low at least 2 bars after the flush low; the bounce high is the top between the two lows
    cand = list(range(lj + 2, n))
    if not cand:
        return False, {"why_not": "3 no retest yet"}
    rj = min(cand, key=lambda j: done[j]["l"])
    mid = list(range(lj + 1, rj))
    if not mid:
        return False, {"why_not": "2 no bounce between the lows"}
    hj = max(mid, key=lambda j: done[j]["h"])
    bounce = (done[hj]["h"] / L - 1) * 100
    need = max(c["bounce_pct"], c["bounce_atr"] * atrp)
    if bounce < need:
        return False, {"why_not": f"2 bounce {bounce:.1f}% < {need:.1f}%"}
    near = (done[rj]["l"] / L - 1) * 100
    if near > c["near_pct"] or near < -c["break_pct"]:
        return False, {"why_not": f"3 retest {near:+.2f}% from the flush low"}
    if rj - fj > c["retest_max"]:
        return False, {"why_not": "3 retest too late (R1 territory)"}
    # 4 weaker: retest volume vs the flush bar
    rv = max(done[j]["v"] for j in range(rj, n))
    if rv > c["retest_vol"] * done[fj]["v"]:
        return False, {"why_not": f"4 retest volume {rv:.0f} not < {c['retest_vol']} x flush {done[fj]['v']:.0f}"}
    # 5 turn
    t_ = fb[m] + fs[m]
    if not (done[-1]["c"] > done[-2]["c"] and t_ and fb[m] / t_ >= c["turn_bs"]):
        return False, {"why_not": "5 no turn bar"}
    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"}
    if (P / vwap - 1) * 100 < -c["max_under_vwap"]:
        return False, {"why_not": "too far under VWAP"}
    return True, {"support": L, "support_m": _minute(done[lj]["t"]), "flush_m": _minute(done[fj]["t"]), "flush_vol": done[fj]["v"], "bounce": round(bounce, 2),
                  "retest_near": round(near, 2), "room": round(room, 2), "vwap": round(vwap, 4)}
