"""
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)
  [v2, 10/22 after CRML 10/03/2025 (-1% first) vs WOLF] the stock's STORY must fit too:
  7 REAL BAR     the trigger bar's volume >= trig_vol_x (0.5) x the stock's normal for that minute (buy share on a
                 1,690-share bar is noise)
  8 NEAR VWAP    price no more than max_under_vwap (2%) under VWAP (far under = the sellers own the day)
  9 TESTED       the bounce off the support before the retest >= max(bounce_pct, bounce_atr x daily ATR %) (0.25 ATR)
  10 NO FAILED PUSH  since the support no bar with >= push_vol_x (2x) normal volume and >= push_bs (75%) buyers that
                 moved the price < push_move (0.3%) (a seller absorbing the buying above)
  11 NOT A FADE  not: the day high made after the first 15 min, >= fade_age (60) min ago, and the price now under the
                 open (the morning rally is being given back)
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,
            "trig_vol_x": 0.5, "max_under_vwap": 2.0, "bounce_atr": 0.25, "push_vol_x": 2.0, "push_bs": 0.75, "push_move": 0.3,
            "fade_age": 60, "story": True}


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
    atrp = (ref or {}).get("atr14") / (ref or {}).get("prev_close") * 100 if (ref or {}).get("atr14") and (ref or {}).get("prev_close") else 0.0
    need_bounce = max(c["bounce_pct"], c["bounce_atr"] * atrp) if c["story"] else c["bounce_pct"]
    if (bounce / sup - 1) * 100 < need_bounce:
        return False, {"why_not": f"9 support not tested: bounce {(bounce / sup - 1) * 100:.1f}% < {need_bounce:.1f}%"}
    # 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, {}
    if c["story"]:
        vpm = (ref or {}).get("vol_per_min") or []
        norm = lambda k: vpm[min(k, len(vpm) - 1)] if vpm else 0
        if norm(m) and done[-1]["v"] < c["trig_vol_x"] * norm(m):
            return False, {"why_not": f"7 trigger bar too small: {done[-1]['v']:.0f} shares = {done[-1]['v'] / norm(m):.1f}x normal"}
        if (P / vwap - 1) * 100 < -c["max_under_vwap"]:
            return False, {"why_not": f"8 too far under VWAP: {(P / vwap - 1) * 100:+.1f}%"}
        m0 = m - (n - 1)                                  # minute of done[0]
        for j in range(i0 + 1, n - 1):
            k = m0 + j; b = done[j]
            t_ = fb[k] + fs[k]
            if norm(k) and b["v"] >= c["push_vol_x"] * norm(k) and t_ and fb[k] / t_ >= c["push_bs"] and (b["c"] / b["o"] - 1) * 100 < c["push_move"]:
                return False, {"why_not": f"10 failed buying push at minute {k}: {b['v']:.0f} sh {fb[k] / t_:.0%} buyers, price {(b['c'] / b['o'] - 1) * 100:+.2f}%"}
        jh = max(range(n), key=lambda j: done[j]["h"])
        if m0 + jh >= 15 and (n - 1 - jh) >= c["fade_age"] and P < done[0]["o"]:
            return False, {"why_not": f"11 fade: day high {done[jh]['h']:.2f} {n - 1 - jh} min ago, price under the open"}
    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)}
