"""
r7_setup.py -- [2026-10-23] The user's setup R7 "PULLBACK IN A MORNING UPTREND, NOT EXTENDED" (from the CRML 10/3/2025
practice chart, ATR 9.9%: a choppy morning climb 8.24 -> 8.79 in steps; the 9:43 high 8.61, pullback on heavy selling
(9:45 2.5x 20% buyers, 9:48 3.4x 36%) to 8.33 -- a higher low above the morning low -- then 9:49 turned up with 69% buyers;
the user's entry "9:48 pullback" -> buy 9:50 open ~8.44, +2% at 9:51). Different from FRMI 9:45 (dropped by the user):
CRML was only +1.3..2.5% over the open, not extended.
  1 UPTREND    a recent high (made within high_age (15) bars) >= max(trend_pct 1.5%, trend_atr 0.2 x ATR %) over the open
  2 PULLBACK   from that high down >= max(pb_pct 1%, pb_atr 0.15 x ATR %) and no more than pb_max (80%) of the climb from the
               morning low to the high
  3 HIGHER LOW the pullback low is above the morning low (the low before the high)
  4 TURN       the trigger bar closes above the bar before with buyers >= turn_bs (60%)
  5 NOT EXTENDED  <= max_open (3%) over the open and <= max_vwap (2%) over VWAP at the trigger (S6 / A1 / A5)
  6 ROOM       the recent high >= room_pct (1.5%) above the close
  safety       >= min_spm shares/min; 9:40-11:00; cool-down 10 min (one trigger per pullback)
When R7 is true these v2 rules do NOT apply: the 15-min buy share / steady trend (the pullback breaks them). Untested.
"""
DEFAULTS = {"high_age": 15, "trend_pct": 1.5, "trend_atr": 0.2, "pb_pct": 1.0, "pb_atr": 0.15, "pb_max": 0.80,
            "turn_bs": 0.60, "max_open": 3.0, "max_vwap": 2.0, "room_pct": 1.5, "min_spm": 2000, "first_m": 10,
            "last_m": 90, "cooldown": 10}


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 < 8:
        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"]
    O = done[0]["o"]
    # 1 the recent high (excluding the trigger bar), within high_age bars
    win = list(range(max(0, n - 1 - c["high_age"]), n - 1))
    jh = max(win, key=lambda j: done[j]["h"])
    H = done[jh]["h"]
    if H < max(x["h"] for x in done[:jh + 1]):
        return False, {"why_not": "1 not at the day high"}
    climb = (H / O - 1) * 100
    if climb < max(c["trend_pct"], c["trend_atr"] * atrp):
        return False, {"why_not": f"1 no uptrend ({climb:.1f}% over the open)"}
    # 2 pullback after the high
    after = done[jh + 1:n - 1] + [done[-1]]
    pbl = min(x["l"] for x in after)
    mlow = min(x["l"] for x in done[:jh + 1])
    pb = (H / pbl - 1) * 100
    if pb < max(c["pb_pct"], c["pb_atr"] * atrp):
        return False, {"why_not": f"2 pullback {pb:.1f}% too small"}
    if (H - pbl) > c["pb_max"] * (H - mlow):
        return False, {"why_not": f"2 pullback too deep ({(H - pbl) / (H - mlow):.0%} of the climb)"}
    # 3 higher low
    if pbl <= mlow:
        return False, {"why_not": "3 no higher low"}
    # 4 turn
    t_ = fb[m] + fs[m]
    P = done[-1]["c"]
    if P <= done[-2]["c"] or not t_ or fb[m] / t_ < c["turn_bs"]:
        return False, {"why_not": "4 no turn bar"}
    # 5 not extended
    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
    if (P / O - 1) * 100 > c["max_open"] or (P / vwap - 1) * 100 > c["max_vwap"]:
        return False, {"why_not": f"5 extended ({(P / O - 1) * 100:+.1f}% open, {(P / vwap - 1) * 100:+.1f}% VWAP)"}
    room = (H / 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": pbl, "support_m": _minute(done[n - len(after) + [x["l"] for x in after].index(pbl)]["t"]),
                  "high": H, "pullback": round(pb, 2), "morning_low": mlow, "room": round(room, 2),
                  "vs_open": round((P / O - 1) * 100, 2), "vs_vwap": round((P / vwap - 1) * 100, 2)}
