"""
r1_setup.py -- [2026-10-22] The user's dynamic setup R1 "RETEST REVERSAL AT SUPPORT" (from the WOLF 11/06/2024 practice chart:
open 13.41, low 12.60 at 9:36, bounce died at VWAP, retest 12.61 at 9:57-9:58 held, 9:59 buyers 40% -> 73% while sell
volume collapsed, close above the base -> buy 12.83, +5% by 13:05). The bot reads the WHOLE movement since the open:
  1 SUPPORT      the lowest low so far, made at least min_age bars ago, followed by a bounce >= bounce_pct
  2 RETEST HELD  the low of the last retest_bars bars came back within near_pct of the support and did not break it
                 by more than break_pct
  3 SELLERS GONE sell volume of the signal bar <= sell_dry x the mean sell volume of the 3 bars before
                 (total volume does NOT need to rise)
  4 BUYERS UP    1-min buy share >= bs_min and >= bs_jump above the mean of the 3 bars before
  5 PRICE UP     the close is above the highest high of the base_bars bars before
  6 ROOM         the higher of VWAP and the open is >= room_pct above the close (they are TARGETS, not blocks)
  safety         >= min_spm shares/min over the last 5 bars; 9:40-14:30; one trigger per support (cool-down)
When R1 is true these v2 rules do NOT apply: RVOL >= 1.5x, 15-min buy share, 15-min steady trend, price >= VWAP, below
the open. Pure function, no orders.
"""
DEFAULTS = {"min_age": 5, "bounce_pct": 1.0, "retest_bars": 6, "near_pct": 0.4, "break_pct": 0.3, "sell_dry": 0.5,
            "bs_min": 0.65, "bs_jump": 0.20, "base_bars": 5, "room_pct": 2.0, "min_spm": 2000, "first_m": 10,
            "last_m": 300, "cooldown": 15}


def check(done, flow, ref, m, c=None):
    """done: finished bars (index = minute since 9:30 for complete data); flow: {'buy': [...], 'sell': [...]} per minute;
    m = minute of the last finished bar. -> (bool, info)"""
    c = {**DEFAULTS, **(c or {})}
    n = len(done)
    if m < c["first_m"] or m >= c["last_m"] or n < c["min_age"] + c["retest_bars"] + 2:
        return False, {}
    fb, fs = flow["buy"], flow["sell"]
    # 1 support: lowest low before the retest window, old enough, then a bounce
    pre = done[: n - c["retest_bars"]]
    i0 = min(range(len(pre)), key=lambda i: pre[i]["l"])
    sup = pre[i0]["l"]
    if n - 1 - i0 < c["min_age"] + c["retest_bars"] - 1:
        return False, {}
    bounce = max(x["h"] for x in done[i0:n - c["retest_bars"] + 1]) if i0 < n - c["retest_bars"] else sup
    if (bounce / sup - 1) * 100 < c["bounce_pct"]:
        return False, {}
    # 2 retest held
    rl = min(x["l"] for x in done[-c["retest_bars"]:])
    near = (rl / sup - 1) * 100
    if near > c["near_pct"] or near < -c["break_pct"]:
        return False, {}
    # 3 sellers gone / 4 buyers up (flow by minute index)
    if m < 3:
        return False, {}
    s_now, s_prev = fs[m], sum(fs[m - 3:m]) / 3
    tot = lambda k: fb[k] + fs[k]
    bs = lambda k: fb[k] / tot(k) if tot(k) else 0.0
    bs_now, bs_prev = bs(m), sum(bs(k) for k in range(m - 3, m)) / 3
    if not (s_prev > 0 and s_now <= c["sell_dry"] * s_prev):
        return False, {}
    if not (bs_now >= c["bs_min"] and bs_now - bs_prev >= c["bs_jump"]):
        return False, {}
    # 5 price up: close above the base
    base_hi = max(x["h"] for x in done[-1 - c["base_bars"]:-1])
    P = done[-1]["c"]
    if P <= base_hi:
        return False, {}
    # 6 room to the targets (VWAP / open)
    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
    target = max(vwap, done[0]["o"])
    room = (target / P - 1) * 100
    if room < c["room_pct"]:
        return False, {}
    if sum(x["v"] for x in done[-5:]) / 5 < c["min_spm"]:
        return False, {}
    return True, {"support": sup, "support_m": i0, "retest_low": rl, "near_pct": round(near, 2), "sell_now": s_now,
                  "sell_prev": round(s_prev), "bs_now": round(bs_now, 2), "bs_prev": round(bs_prev, 2), "base_hi": base_hi,
                  "vwap": round(vwap, 4), "open": done[0]["o"], "room": round(room, 2)}
