"""
r2_setup.py -- [2026-10-22] The user's setup R2 "CALM-STOCK BASE AT A HIGHER LOW" (from the SNAP 12/30/2024 practice chart:
calm stock, ATR 4.8%, gap -2.5%; opening dip to 10.56 at 9:32, bounce to 10.77, slow drift back into a flat base at
10.61-10.66 (a HIGHER low) where buyers kept absorbing the selling (15-min buy share 53-58%, price flat), then the climb to
the previous close 10.99 = the gap fill. Best entry inside the base, 10.62-10.63 at 10:07-10:10 -> +2% at 11:04, +3.4% high).
On a calm stock a 2% move needs an EARLY entry: R2 buys inside the base, it does not wait for the breakout bar.
  0 CALM         daily ATR % < max_atr (8%)
  1 SUPPORT      the lowest low so far, made >= min_age bars ago, then a bounce >= max(bounce_pct, bounce_atr x ATR %)
  2 HIGHER LOW   the low of the base is AT or ABOVE the support (no break below by more than break_pct) and no more than
                 hl_atr x ATR % above it -- [10/22, NVAX 12/13/2024] tightened 0.25 -> 0.10 ATR: the base must sit AT the
                 support (NVAX 10:01 base 1.0% above, mid-range -> -1% first; NVAX 11:00-11:06 base 0.2% above = the user's
                 entry -> +2% first; SNAP 0.43% above, limit 0.48%)
  3 FLAT BASE    the last base_bars bars stay inside a range <= base_atr x ATR % (price holding, not sliding)
  4 ABSORPTION   buy share over the base >= base_bs (50%): buyers matching or beating the sellers while price holds
  5 NOT FALLING  the trigger bar closes >= the bar before and its buy share >= trig_bs (50%)
  5b LOW IN BASE the close is in the lower max_base_pos (50%) of the base range (on a calm stock the 2% is made by buying
                 the bottom of the base, not its top)
  6 ROOM         the highest target above (VWAP, the open, the previous close, today's high so far) >= room_pct above
  7 STORY        >= min_spm shares/min; no more than max_under_vwap under VWAP; not a fade (day high after the first 15 min,
                 >= 60 min ago, price under the open); 9:45-14:30; one trigger per base (cool-down)
When R2 is true these v2 rules do NOT apply: RVOL >= 1.5x, 15-min buy share >= 55%, 15-min steady trend, price >= VWAP,
below the open, calm-stock (min_atr) avoid rule. Pure function, no orders.
"""
DEFAULTS = {"max_atr": 8.0, "min_age": 10, "bounce_pct": 0.8, "bounce_atr": 0.25, "break_pct": 0.1, "hl_atr": 0.10,
            "base_bars": 10, "base_atr": 0.2, "base_bs": 0.50, "trig_bs": 0.50, "room_pct": 2.0, "min_spm": 2000,
            "max_under_vwap": 1.5, "max_base_pos": 0.5, "fade_age": 60, "first_m": 15, "last_m": 300, "cooldown": 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 < c["min_age"] + c["base_bars"]:
        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["max_atr"]:
        return False, {"why_not": "0 not a calm stock"}
    fb, fs = flow["buy"], flow["sell"]
    m0 = m - (n - 1)
    base = done[-c["base_bars"]:]
    pre = done[:n - c["base_bars"]]
    i0 = min(range(len(pre)), key=lambda i: pre[i]["l"])
    sup = pre[i0]["l"]
    if n - 1 - i0 < c["min_age"]:
        return False, {"why_not": "1 support too young"}
    bounce = max(x["h"] for x in done[i0:n - c["base_bars"] + 1])
    need_b = max(c["bounce_pct"], c["bounce_atr"] * atrp)
    if (bounce / sup - 1) * 100 < need_b:
        return False, {"why_not": f"1 bounce {(bounce / sup - 1) * 100:.1f}% < {need_b:.1f}%"}
    blo = min(x["l"] for x in base); bhi = max(x["h"] for x in base)
    hl = (blo / sup - 1) * 100
    if hl < -c["break_pct"] or hl > c["hl_atr"] * atrp:
        return False, {"why_not": f"2 base low {hl:+.2f}% vs support (allowed 0..{c['hl_atr'] * atrp:.2f}%)"}
    rng = (bhi / blo - 1) * 100
    if rng > c["base_atr"] * atrp:
        return False, {"why_not": f"3 base not flat: range {rng:.2f}% > {c['base_atr'] * atrp:.2f}%"}
    ks = range(m - c["base_bars"] + 1, m + 1)
    B, S = sum(fb[k] for k in ks), sum(fs[k] for k in ks)
    bs_base = B / (B + S) if B + S else 0.0
    if bs_base < c["base_bs"]:
        return False, {"why_not": f"4 no absorption: base buy share {bs_base:.0%}"}
    t_ = fb[m] + fs[m]
    if done[-1]["c"] < done[-2]["c"] or not t_ or fb[m] / t_ < c["trig_bs"]:
        return False, {"why_not": "5 trigger bar falling or sellers"}
    P = done[-1]["c"]
    if bhi > blo and (P - blo) / (bhi - blo) > c["max_base_pos"]:
        return False, {"why_not": f"5b price high in the base ({(P - blo) / (bhi - blo):.0%})"}
    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
    targets = [vwap, done[0]["o"], max(x["h"] for x in done)] + ([ref["prev_close"]] if ref.get("prev_close") else [])
    room = (max(targets) / P - 1) * 100
    if room < c["room_pct"]:
        return False, {"why_not": f"6 room {room:.1f}% < {c['room_pct']}%"}
    if sum(x["v"] for x in done[-5:]) / 5 < c["min_spm"]:
        return False, {"why_not": "7 thin"}
    if (P / vwap - 1) * 100 < -c["max_under_vwap"]:
        return False, {"why_not": f"7 {(P / vwap - 1) * 100:+.1f}% under VWAP"}
    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": "7 fade"}
    vpm = ref.get("vol_per_min") or []
    defended = any(vpm and done[j]["v"] >= 2 * max(vpm[min(m0 + j, len(vpm) - 1)], 1) and (fb[m0 + j] + fs[m0 + j]) and
                   fb[m0 + j] / (fb[m0 + j] + fs[m0 + j]) >= 0.65 and done[j]["l"] <= blo * 1.002 for j in range(n - c["base_bars"], n))
    return True, {"defended_low": defended, "support": sup, "support_m": m0 + i0, "base_lo": blo, "base_hi": bhi, "base_range": round(rng, 2),
                  "higher_low": round(hl, 2), "base_bs": round(bs_base, 2), "room": round(room, 2), "vwap": round(vwap, 4),
                  "atr": round(atrp, 1)}
