"""
momentum_entry.py -- [2026-10-22] The user's design: a minute-by-minute BUY-NOW-or-WAIT decision that works TOGETHER with
the situations, using only the last 5 finished bars (no 15-bar window needed -> it can act from 9:35).

  1. SIGNAL (last 5 finished bars b1..b5, oldest -> newest)
       volume rising      mean volume of b4-b5 > mean of b1-b3
       buy share rising   buy share of b4-b5 > b1-b3, and >= min_bs (50%)
       price rising       close b5 > close b3 > close b1
  2. BLOCKERS (from the situations, avoid rules and do-not-trade list), in 3 classes:
       HARD       never overridden -- the signal itself may be fake or the trade cannot be executed well:
                  S1 flip noise, S2 weak spike, S3 block print, thin (< min_spm shares/min over 5 bars),
                  wide spread, after last_buy (14:30)
       EXTENDED   never overridden -- buying the top: S6 > 3% over the open, > 2% over VWAP
       SOFT       context that usually means "wait", but a clear positive momentum can overrule it:
                  calm stock (ATR < 8%), choppy (>= 3 Vs), S8 under resistance, S9 under the previous close,
                  low RVOL, heavy volume / recent climax, lower low by 10:30, flat bars at the low, gap > 10%
  3. MOMENTUM (all must hold to overrule SOFT blockers) -- from the 5 big-loser study (10/22): winners were an early
     push from the middle of the range, close to VWAP, on volume; losers were bought late, high in the range:
       M1 fresh push     close up >= push_pct (0.5%) over the last 5 bars
       M2 room in range  price in the lower range_max (65%) of today's range so far
       M3 not stretched  <= vwap_max (1%) over VWAP
       M4 volume         last 5 minutes' volume >= vol_x (1.5x) the stock's normal for those minutes
  DECISION each minute:  no signal -> WAIT | HARD or EXTENDED -> WAIT | SOFT only + momentum -> BUY (override) |
                         SOFT only, no momentum -> WAIT (re-checked next bar) | nothing -> BUY
Pure functions; no orders. Record-only use first (2-year test before anything live).
"""
DEFAULTS = {
    "min_bs": 0.50, "min_bars": 5, "first_m": 5, "last_buy_m": 300, "min_spm": 2000, "max_spread_pct": 1.0,
    "max_open_pct": 3.0, "max_vwap_pct": 2.0, "min_atr_pct": 8.0, "max_vs": 3, "min_room_pct": 5.0,
    "prev_close_zone": (0.5, 3.0), "min_rvol": 1.5, "heavy_vol_x": 5.0, "climax_x": 10.0, "max_gap_pct": 10.0,
    "push_pct": 0.5, "range_max": 0.65, "vwap_max": 1.0, "vol_x": 1.5,
    "override": True,
}


def _bs(fl):
    b = sum(x[0] for x in fl if x); s = sum(x[1] for x in fl if x)
    return b / (b + s) if b + s else None


def signal(done, flow5, c):
    """done: finished bars; flow5: [(buy, sell)] of the same last 5 bars (None if unknown)"""
    if len(done) < c["min_bars"]:
        return False, {}
    b = done[-5:]
    v_old, v_new = sum(x["v"] for x in b[:3]) / 3, sum(x["v"] for x in b[3:]) / 2
    bs_old, bs_new = _bs(flow5[:3]), _bs(flow5[3:])
    ok = (v_new > v_old and bs_old is not None and bs_new is not None and bs_new > bs_old and bs_new >= c["min_bs"]
          and b[4]["c"] > b[2]["c"] > b[0]["c"])
    return ok, {"vol_x5": v_new / max(v_old, 1), "bs_new": bs_new, "bs_old": bs_old}


def momentum(done, ref, m, c):
    P = done[-1]["c"]
    lo = min(x["l"] for x in done); hi = max(x["h"] for x in done)
    pv = sum((x["h"] + x["l"] + x["c"]) / 3 * x["v"] for x in done); cv = sum(x["v"] for x in done)
    vwap_pct = (P / (pv / cv) - 1) * 100 if cv else 0.0
    vpm = (ref or {}).get("vol_per_min") or []
    norm5 = sum(vpm[max(0, m - 4):m + 1]) if vpm else 0
    v5 = sum(x["v"] for x in done[-5:])
    push = (P / done[-6]["c"] - 1) * 100 if len(done) >= 6 else (P / done[0]["o"] - 1) * 100
    rpos = (P - lo) / (hi - lo) if hi > lo else 0.5
    m1, m2, m3 = push >= c["push_pct"], rpos <= c["range_max"], vwap_pct <= c["vwap_max"]
    m4 = (v5 / norm5 >= c["vol_x"]) if norm5 else False
    return m1 and m2 and m3 and m4, {"push": round(push, 2), "range_pos": round(rpos, 2), "vwap_pct": round(vwap_pct, 2),
                                     "vol5_x": round(v5 / norm5, 2) if norm5 else None, "M": [m1, m2, m3, m4]}


def blockers(done, ref, m, metrics, sit_held, spread_pct, c):
    """-> (hard, extended, soft) lists. sit_held: situation names that would hold now (S1 / S2 / S3 / S8 / S9)."""
    hard, ext, soft = [], [], []
    P = done[-1]["c"]; O = done[0]["o"]
    for s in sit_held:
        (hard if s in ("S1", "S2", "S3") else ext if s == "S6" else soft).append(s)
    if m + 1 >= c["last_buy_m"]:
        hard.append("late (after 14:30)")
    if sum(x["v"] for x in done[-5:]) / 5 < c["min_spm"]:
        hard.append("thin")
    if spread_pct is not None and spread_pct > c["max_spread_pct"]:
        hard.append("wide spread")
    if (P / O - 1) * 100 > c["max_open_pct"] and "S6" not in ext:
        ext.append(">3% over open")
    pv = sum((x["h"] + x["l"] + x["c"]) / 3 * x["v"] for x in done); cv = sum(x["v"] for x in done)
    if cv and (P / (pv / cv) - 1) * 100 > c["max_vwap_pct"]:
        ext.append(">2% over VWAP")
    ref = ref or {}
    atrp = ref["atr14"] / ref["prev_close"] * 100 if ref.get("atr14") and ref.get("prev_close") else None
    if atrp is not None and atrp < c["min_atr_pct"]:
        soft.append("calm")
    rvol = metrics.get("rvol_sofar")
    if rvol is not None and rvol < c["min_rvol"]:
        soft.append("low RVOL")
    vpm = ref.get("vol_per_min") or []
    if vpm and any(x["v"] >= c["climax_x"] * max(vpm[min(i, len(vpm) - 1)], 1) for i, x in enumerate(done) if i >= len(done) - 30):
        soft.append("recent climax")
    if ref.get("prev_close") and (O / ref["prev_close"] - 1) * 100 > c["max_gap_pct"]:
        soft.append("gap > 10%")
    if len(done) >= 60 and min(x["l"] for x in done[30:60]) < min(x["l"] for x in done[:30]):
        soft.append("lower low by 10:30")
    L = [x["l"] for x in done]; H = [x["h"] for x in done]; nv = 0
    for j in range(15, len(done) - 3):
        if L[j] <= min(L[j - 3:j + 4]) and L[j - 1] != L[j] and max(H[max(0, j - 30):j]) / L[j] - 1 >= 0.01:
            nv += 1
    if nv >= c["max_vs"]:
        soft.append("choppy")
    lo30 = min(L[-30:])
    if sum(1 for x in done[-5:] if x["h"] == x["l"] and x["v"] > 0) >= 2 and P <= lo30 * 1.01:
        soft.append("flat bars at low")
    return hard, ext, soft


def decide(done, flow5, ref, m, metrics, sit_held=(), spread_pct=None, cfg=None):
    """-> (action 'BUY' / 'WAIT', why, info). m = index of the last finished bar (minutes since 9:30)."""
    c = {**DEFAULTS, **(cfg or {})}
    if m + 1 < c["first_m"]:
        return "WAIT", "first 5 bars", {}
    ok, info = signal(done, flow5, c)
    if not ok:
        return "WAIT", "no signal", info
    hard, ext, soft = blockers(done, ref, m, metrics or {}, list(sit_held), spread_pct, c)
    mom, minfo = momentum(done, ref, m, c)
    info.update(minfo, hard=hard, ext=ext, soft=soft)
    if hard or ext:
        return "WAIT", "blocked: " + ", ".join(hard + ext), info
    if soft and not (c["override"] and mom):
        return "WAIT", "wait for momentum: " + ", ".join(soft), info
    return "BUY", ("momentum overrides: " + ", ".join(soft)) if soft else "all clear", info
