"""
r1c_setup.py -- [2026-10-23] The user's setup R1C "FIRST REVERSAL AFTER A FLUSH" (from QUBT 5/20/2025: opened 12.71, sold off
to 11.33 at 9:49 = -10.4% from the open, ~1.5x the daily ATR, just above the previous day's low 11.20, no climax bar; 9:50 turn
bar 72% buyers on 1.28x volume closing 11.54; the user's buy = right there, the retest at 9:56 held 11.35; ran to 12.10).
Unlike R1A it does NOT wait for the retest -- it buys the first strong turn bar off the flush low.
  1 DROP       the open -> flush low drop >= drop_atr (1.0) x the daily ATR (the day's selling is used up)
  2 FRESH LOW  the flush low (the lowest low of the day so far) is at most low_age (2) bars before the trigger bar
  3 SUPPORT    the flush low is above the previous day's low (QBTS-type breakdowns under it are N2 no-trades)
  4 NO CLIMAX  no bar in the last 15 with >= climax_x (5x) the day's 15-bar average volume (climax = A9, don't catch it)
  5 SELLERS    15-min buy share >= min_bs15 (45%) -- sellers not in control of the bigger window (N3)
  6 TURN BAR   the trigger bar closes above the bar before, buyers >= turn_bs (60%), volume >= turn_vol (1.0) x the 15-bar
               average, close in the upper half of its range
  safety       >= min_spm shares/min over 5 bars; 9:40-14:30; one trigger per flush (cool-down)
STOP = under the flush low (info "support"). Exit to pair with it: exit_x1.py (stall exit).
Untested on 2 years. Pure function, no orders.
"""
DEFAULTS = {"drop_atr": 1.0, "low_age": 2, "climax_x": 5.0, "min_bs15": 0.45, "turn_bs": 0.60, "turn_vol": 1.0,
            "turn_pos": 0.5, "min_spm": 2000, "first_m": 10, "last_m": 300, "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 < 16 or not ref.get("atr14"):
        return False, {}
    fb, fs = flow["buy"], flow["sell"]
    O = done[0]["o"]
    lj = min(range(n), key=lambda j: done[j]["l"]); L = done[lj]["l"]
    # 2 fresh low
    if not (1 <= n - 1 - lj <= c["low_age"]):
        return False, {"why_not": "2 the day's low is not 1-2 bars old"}
    # 1 drop
    drop = O - L
    if drop < c["drop_atr"] * ref["atr14"]:
        return False, {"why_not": f"1 drop {drop:.3g} < {c['drop_atr']} x ATR {ref['atr14']:.3g}"}
    # 3 support
    if ref.get("prev_low") and L <= ref["prev_low"]:
        return False, {"why_not": f"3 flush low {L} under the previous day's low {ref['prev_low']}"}
    # 4 no climax
    for j in range(max(1, n - 15), n):
        w = done[max(0, j - 15):j]
        if w and done[j]["v"] >= c["climax_x"] * sum(x["v"] for x in w) / len(w):
            return False, {"why_not": f"4 climax bar at {_minute(done[j]['t'])}"}
    # 5 sellers not in control (15 min)
    B = sum(fb[max(0, m - 14):m + 1]); S = sum(fs[max(0, m - 14):m + 1])
    bs15 = B / (B + S) if B + S else 0.5
    if bs15 < c["min_bs15"]:
        return False, {"why_not": f"5 15-min buy share {bs15:.0%}"}
    # 6 turn bar
    b, p = done[-1], done[-2]
    t_ = fb[m] + fs[m]; bs1 = fb[m] / t_ if t_ else 0
    av = sum(x["v"] for x in done[-16:-1]) / 15
    pos = (b["c"] - b["l"]) / (b["h"] - b["l"]) if b["h"] > b["l"] else 0.5
    if not (b["c"] > p["c"] and bs1 >= c["turn_bs"] and b["v"] >= c["turn_vol"] * av and pos >= c["turn_pos"]):
        return False, {"why_not": f"6 no turn bar (up {b['c'] > p['c']}, buyers {bs1:.0%}, vol {b['v'] / av if av else 0:.2f}x, pos {pos:.2f})"}
    if sum(x["v"] for x in done[-5:]) / 5 < c["min_spm"]:
        return False, {"why_not": "thin"}
    return True, {"support": L, "support_m": _minute(done[lj]["t"]), "drop_atr": round(drop / ref["atr14"], 2),
                  "bs15": round(bs15, 3), "turn_bs": round(bs1, 3), "turn_vol_x": round(b["v"] / av, 2) if av else None}
