"""
r11_setup.py -- [2026-10-25] The user's setup R11 "THE TURN AT A LEVEL" (pattern group G8 "higher low under VWAP", from the user's
marks on 15 practice charts reports/practice/groups/G8_practice.pdf + G8_marks.json: SOS, REBN, CXM, USAR, ONDS, NVA, TMC, NAMM,
LWLG x2, XOS; blocked: SLS, CPSH, DSY; too thin: CBIO).
  1 FRESH LOW    the lowest low of the last `lookback` (20) bars was made 1..fresh_max (15) bars ago (the pullback / flush low)
  2 UNDER VWAP   that low is >= under_vwap (1%) under the session VWAP
  3 HOLDS        no lower low since; the low is above the previous day's low (N2)
  4 THE TURN     >= turn_need (2) of the last turn_n (3) bars with 1-min buy share >= turn_bs (60%), the last bar one of them or
                 closing at/above the bar before; 5-min buy share >= bs5_min (45%) AND >= bs5_rise (15 pts) above its lowest value of
                 the last 10 bars, or >= bs5_hi (55%); the close 0.3%..max(off_max 4%, off_atr 0.5 x daily ATR %) above the low
  [v2 10/25 from the marks check: no "green bar" rule (SOS / NVA / TMC turned on buyer-heavy red bars), 5-min buy share may still
   be under 50% if it is rising (SOS 43-47%), room off the low scales with ATR (NVA 5.3%), climax = SELLING climax only (CXM's
   breakout bar and TMC's absorption were 10-11x BUYING), breakdown vs the day low from BEFORE the move (CPSH)]
  BLOCKS (the user's "no" charts):
    breakdown    a new day low after 11:00 more than breakdown_pct (3%) under the earlier day low      (CPSH, DSY)
    waterfall    a drop of >= waterfall_pct (8%) within 10 bars into the low                          (DSY)
    staircase    >= 4 lower lows in a row of the 30-min windows since the open AND no close above VWAP in the last 120 bars (SLS)
    climax       a bar >= climax_x (10x) its normal 1-min volume in the last 30 bars                   (SLS, DSY)
    thin         under min_spm (2,000) shares/min over 5 bars                                          (CBIO)
STOP = under the low (info "support"). EXIT (test): level exit -- the nearest of VWAP / open / previous close above the buy is the
target; a stall there sells; back above VWAP -> C3. Pure function, no orders.
"""
DEFAULTS = {"lookback": 20, "fresh_max": 15, "under_vwap": 1.0, "turn_n": 3, "turn_need": 2, "turn_bs": 0.60, "bs5_min": 0.45, "bs5_rise": 0.15, "bs5_hi": 0.55,
            "off_min": 0.3, "off_max": 4.0, "off_atr": 0.5, "climax_bs": 0.40, "breakdown_pct": 3.0, "waterfall_pct": 8.0, "climax_x": 10.0, "min_spm": 2000,
            "first_m": 5, "last_m": 330, "cooldown": 20}


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 < 6:
        return False, {}
    w0 = max(0, n - c["lookback"])
    li = min(range(w0, n), key=lambda i: done[i]["l"]); L = done[li]["l"]
    mins = [_minute(x["t"]) for x in done]
    age = n - 1 - li
    if not (1 <= age <= c["fresh_max"]):
        return False, {"why_not": f"1 low age {age}"}
    pv = cv = 0.0; vw = []
    for x in done:
        pv += (x["h"] + x["l"] + x["c"]) / 3 * x["v"]; cv += x["v"]; vw.append(pv / cv if cv else x["c"])
    if c.get("mode") == "near":   # [R12] the low is AT a level: VWAP +/- near_vwap, or the open / previous close +/- near_level
        lv = [vw[li], done[0]["o"]] + ([ref["prev_close"]] if ref.get("prev_close") else [])
        opening = mins[li] < 10 and abs(L / done[0]["o"] - 1) * 100 <= c.get("near_open_early", 2.5)   # VWAP not settled yet
        if not (opening or abs(L / vw[li] - 1) * 100 <= c.get("near_vwap", 1.5) or
                any(abs(L / x - 1) * 100 <= c.get("near_level", 0.5) for x in lv[1:])):
            return False, {"why_not": f"2 low not at VWAP / open / prev close ({(L / vw[li] - 1) * 100:+.1f}% vs VWAP)"}
    elif L > vw[li] * (1 - c["under_vwap"] / 100):
        return False, {"why_not": f"2 low only {(L / vw[li] - 1) * 100:+.1f}% vs VWAP"}
    if ref.get("prev_low") and L < ref["prev_low"]:
        # [10/25 LCID] a small undercut (<= prev_low_undercut %) that is already reclaimed is allowed
        if not (L >= ref["prev_low"] * (1 - c.get("prev_low_undercut", 0.0) / 100) and done[-1]["c"] > ref["prev_low"]):
            return False, {"why_not": "3 under the previous day's low"}
    fb, fs = flow["buy"], flow["sell"]
    def bs(i0, i1):
        B = sum(fb[mins[i]] for i in range(i0, i1 + 1)); S = sum(fs[mins[i]] for i in range(i0, i1 + 1))
        return B / (B + S) if B + S else 0.0
    t0 = n - c["turn_n"]
    strong = sum(1 for i in range(max(li + 1, t0), n) if bs(i, i) >= c["turn_bs"])
    b = done[-1]; P = b["c"]
    if strong < c["turn_need"] or not (bs(n - 1, n - 1) >= c["turn_bs"] or b["c"] >= done[-2]["c"]):
        return False, {"why_not": f"4 turn: {strong} strong bars"}
    def bs5_at(mm):
        B = sum(fb[max(0, mm - 4):mm + 1]); S = sum(fs[max(0, mm - 4):mm + 1]); return B / (B + S) if B + S else 0.5
    bs5 = bs5_at(m); lo5 = min(bs5_at(mm) for mm in range(max(0, m - 10), m + 1))
    if not (bs5 >= c["bs5_hi"] or (bs5 >= c["bs5_min"] and bs5 - lo5 >= c["bs5_rise"])):
        return False, {"why_not": f"4 5-min buy share {bs5:.0%} (low {lo5:.0%})"}
    off = (P / L - 1) * 100
    atrp = ref["atr14"] / ref["prev_close"] * 100 if ref.get("atr14") and ref.get("prev_close") else 0
    if not (c["off_min"] <= off <= max(c["off_max"], c["off_atr"] * min(atrp, 25))):
        return False, {"why_not": f"4 {off:.1f}% off the low"}
    # blocks
    if li > 20:
        prior = min(x["l"] for x in done[:li - 20])
        if mins[li] >= 90 and L < prior * (1 - c["breakdown_pct"] / 100):
            return False, {"why_not": f"BLOCK breakdown {(L / prior - 1) * 100:.1f}% under the earlier low after 11:00"}
    top = max(x["h"] for x in done[max(0, li - 10):li + 1])
    if (L / top - 1) * 100 <= -c["waterfall_pct"]:
        return False, {"why_not": f"BLOCK waterfall {(L / top - 1) * 100:.1f}% in 10 bars"}
    lows = []
    for s0 in range(0, mins[-1] + 1, 30):
        seg = [x["l"] for x, mm in zip(done, mins) if s0 <= mm < s0 + 30]
        if seg:
            lows.append(min(seg))
    run = 0
    for a_, b_ in zip(lows, lows[1:]):
        run = run + 1 if b_ < a_ else 0
    if run >= 4 and not any(done[i]["c"] > vw[i] for i in range(max(0, n - 120), n)):
        return False, {"why_not": "BLOCK staircase down"}
    vpm = ref.get("vol_per_min") or []
    for i in range(max(0, n - 30), n):
        k = mins[i]
        if (0 <= k < len(vpm) and vpm[k] and done[i]["v"] >= c["climax_x"] * vpm[k] and bs(i, i) < c["climax_bs"]
                and done[i]["c"] < done[i]["o"] and i <= li):
            return False, {"why_not": f"BLOCK selling climax bar {done[i]['v'] / vpm[k]:.0f}x"}
    if sum(x["v"] for x in done[-5:]) / 5 < c["min_spm"]:
        return False, {"why_not": "BLOCK thin"}
    return True, {"support": L, "support_m": mins[li], "low_vs_vwap": round((L / vw[li] - 1) * 100, 2), "off_low": round(off, 2),
                  "bs5": round(bs5, 3), "strong": strong, "vwap": round(vw[-1], 4), "open": done[0]["o"], "prev_close": ref.get("prev_close")}
