"""
r3_setup.py -- [2026-10-22] The user's setup R3 "OPENING PUSH -> FIRST PULLBACK HOLDS -> TURN" (from the UUUU 6/18/2025
practice chart, the user's entry 9:33-9:36: opening print 5.76 bought straight back to 5.93-5.95 in 2 minutes, first
pullback to 5.81 held above the opening low with buyers still 50-57%, 9:34 turned up with 65% buyers -> buy 9:35 open
5.87, +2% at 9:37). Works on the first bars of the day, when the 15-bar indicators do not exist yet.
  1 PUSH       within the first push_bars (3) bars, a rise of >= max(push_pct 1%, push_atr 0.15 x daily ATR %) off the
               opening low, with buyers >= push_bs (50%) on the push bars (the bars AFTER the low bar -- the opening print is
               not counted)
  2 HOLDS      the pullback after the push high retraces <= max_retrace (75%) of the push and stays ABOVE the opening low
  3 NO DUMP    buyers on the pullback bars >= pb_bs (45%) -- profit-taking, not selling
  4 TURN       the trigger bar closes above the bar before with buyers >= turn_bs (55%) and is still under the push high
               (buying the turn, not the breakout) -> buy the next open
  5 MOVER      daily ATR % >= min_atr (5%) -- the stock usually moves enough for +2%
  safety       >= min_spm shares/min; trigger only from bar first_m to last_m (9:33-9:42); one trigger per day
When R3 is true these v2 rules do NOT apply: the 15-bar wait, RVOL, 15-min buy share / steady trend, VWAP band.
Untested on 2 years. Pure function, no orders.
"""
DEFAULTS = {"push_bars": 3, "push_pct": 1.0, "push_atr": 0.15, "push_bs": 0.50, "max_retrace": 0.75, "pb_bs": 0.45,
            "turn_bs": 0.55, "min_atr": 5.0, "min_spm": 2000, "first_m": 3, "last_m": 12, "cooldown": 999}


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 != m + 1 or n < c["push_bars"] + 2:
        return False, {}
    atrp = ref["atr14"] / ref["prev_close"] * 100 if ref.get("atr14") and ref.get("prev_close") else None
    if atrp is None or atrp < c["min_atr"]:
        return False, {"why_not": "5 not a mover (ATR)"}
    fb, fs = flow["buy"], flow["sell"]
    bs = lambda a, b: (sum(fb[a:b + 1]) / max(sum(fb[a:b + 1]) + sum(fs[a:b + 1]), 1e-9))
    # 1 push: the opening low, then the push high inside the first push_bars bars (high after the low)
    pb = c["push_bars"]
    i_low = min(range(pb), key=lambda i: done[i]["l"])
    L0 = done[i_low]["l"]
    i_hi = max(range(i_low, pb), key=lambda i: done[i]["h"])
    H = done[i_hi]["h"]
    push = (H / L0 - 1) * 100
    need = max(c["push_pct"], c["push_atr"] * atrp)
    if push < need:
        return False, {"why_not": f"1 push {push:.1f}% < {need:.1f}%"}
    if bs(i_low + 1 if i_hi > i_low else i_low, i_hi) < c["push_bs"]:
        return False, {"why_not": "1 push without buyers"}
    if i_hi >= n - 2:
        return False, {"why_not": "2 no pullback yet"}
    # 2 holds
    pbl = min(x["l"] for x in done[i_hi + 1:])
    retr = (H - pbl) / (H - L0)
    if pbl <= L0 or retr > c["max_retrace"]:
        return False, {"why_not": f"2 pullback too deep ({retr:.0%} of the push)"}
    # 3 no dump on the pullback (bars after the high, before the trigger bar)
    if n - 2 > i_hi and bs(i_hi + 1, m - 1) < c["pb_bs"]:
        return False, {"why_not": "3 sellers dumped on the pullback"}
    # 4 turn
    t_ = fb[m] + fs[m]
    if not (done[-1]["c"] > done[-2]["c"] and t_ and fb[m] / t_ >= c["turn_bs"] and done[-1]["c"] < H):
        return False, {"why_not": "4 no turn bar"}
    if sum(x["v"] for x in done) / n < c["min_spm"]:
        return False, {"why_not": "thin"}
    return True, {"support": L0, "support_m": i_low, "push_high": H, "push_pct": round(push, 2), "pullback_low": pbl,
                  "retrace": round(retr, 2), "room": round((H / done[-1]["c"] - 1) * 100, 2), "atr": round(atrp, 1)}
