"""
dv1_setup.py -- [2026-11-16] The user's DEEP-V FIRST CROSS (rules note RN-13, "plain", first deep V of the day only), added to
EV3 as setup "DV1" so it buys next to R3 and sells with EV3's exit (stop under the V low, give-back armed at +2%, C3, 15:55).
The user 11/16: "B, using EV3's exit -- just the plain entry that we tested, and the big deep first V only".
Same logic as the 2-year test (scratchpad star/rules30.py base13 + stock_logic.profile), finished regular-session bars only:
  own candle  u = median 1-min bar range (high-low, % of close) of all bars so far today (min 0.02%)
  CROSS       EMA9 crosses above EMA20 on the last finished bar (EMA on closes from the 9:30 bar)
  DEEP        EMA9 was <= EMA20 for >= min_under (20) bars before the cross, AND the dip = (1 - V low / high) in own candles
              >= min_dip_u (8), V low = lowest low of the run under (plus 1 bar before), high = highest high of the 60 bars
              up to the V low
  FIRST       no earlier deep-V cross today would have bought (inside the window, guards passed) -- recomputed from the bars
              every time, so a restart does not forget it
  WINDOW      the buy bar (next bar) is 9:35-15:00 (minute 5..330)
  GUARDS      (user 11/07, all entry tests) no buy if: the day opened > 40% over the previous close; the last 3 bars' volume
              > 50x the normal for that time; the last 15 bars < 10,000 shares/min
  No other filter (RN-14..RN-27 off, EV3's no-trade gate exempt via config).
2-year entry-only check (60-min hold, -0.2% cost): first deep V 3,798 / 3,941 buys, diff +2.3 / +0.2, net -0.15 / -0.24 --
below cost; EV3's exit on these buys is UNTESTED. Paper only. Pure function, no orders.
"""
import statistics
from datetime import datetime, timezone
from zoneinfo import ZoneInfo

ET = ZoneInfo("America/New_York")

DEFAULTS = {"min_under": 20, "min_dip_u": 8.0, "hi_look": 60, "first_buy_m": 5, "last_buy_m": 330,
            "max_gap": 40.0, "max_v3x": 50.0, "min_spm15": 10000, "cooldown": 1}


def _ema(x, n):
    k = 2 / (n + 1); o = [x[0]]
    for v in x[1:]:
        o.append(o[-1] + k * (v - o[-1]))
    return o


def _minute(t):
    if not isinstance(t, datetime):
        t = datetime.fromtimestamp(t, timezone.utc)
    t = t.astimezone(ET)
    return (t.hour - 9) * 60 + t.minute - 30


def check(done, flow, ref, m, c=None):
    c = {**DEFAULTS, **(c or {})}
    ref = ref or {}
    reg = [b for b in done if 0 <= _minute(b["t"]) < 390]
    n = len(reg)
    if n < 11 or _minute(reg[0]["t"]) > 2 or not ref.get("prev_close"):
        return False, {}
    i = n - 1
    M = [_minute(b["t"]) for b in reg]
    if not (c["first_buy_m"] <= M[i] + 1 <= c["last_buy_m"]):
        return False, {}
    gap = (reg[0]["o"] / ref["prev_close"] - 1) * 100
    if gap > c["max_gap"]:
        return False, {"why_not": f"guard: gap {gap:.0f}% > {c['max_gap']:.0f}%"}
    C = [b["c"] for b in reg]; H = [b["h"] for b in reg]; L = [b["l"] for b in reg]; V = [b["v"] for b in reg]
    E9, E20 = _ema(C, 9), _ema(C, 20)
    if not (E9[i] > E20[i] and E9[i - 1] <= E20[i - 1]):
        return False, {}
    rng = [(H[k] - L[k]) / C[k] * 100 if C[k] else 0 for k in range(n)]
    vpm = ref.get("vol_per_min") or []

    def ok(k):                                    # guards at bar k (the buy is at k + 1)
        w15 = V[max(0, k - 14):k + 1]
        if sum(w15) / len(w15) < c["min_spm15"]:
            return False, f"guard: {sum(w15) / len(w15):.0f} sh/min < {c['min_spm15']}"
        if len(vpm) >= 390:
            ks = range(max(0, k - 2), k + 1)
            norm = sum(max(float(vpm[M[q]]), 1.0) for q in ks)
            if sum(V[q] for q in ks) / norm > c["max_v3x"]:
                return False, f"guard: last-3-bar volume > {c['max_v3x']:.0f}x normal"
        return True, ""

    def deep(j):                                  # cross at bar j -> (deep?, info)
        below = 0; q = j - 1
        while q >= 0 and E9[q] <= E20[q]:
            below += 1; q -= 1
        a = max(0, j - below - 1)
        lo = min(range(a, j + 1), key=lambda k: L[k])
        hb = max(0, lo - c["hi_look"])
        hi = max(range(hb, lo + 1), key=lambda k: H[k])
        u = max(statistics.median(rng[:j + 1]), 0.02)
        dip_u = (1 - L[lo] / H[hi]) * 100 / u if H[hi] else 0
        return below >= c["min_under"] and dip_u >= c["min_dip_u"], dict(below=below, dip_u=round(dip_u, 2), u=round(u, 3),
                                                                        v_low=L[lo], v_high=H[hi])

    d, info = deep(i)
    if not d:
        return False, {}
    g, why = ok(i)
    if not g:
        return False, {"why_not": why, **info}
    for j in range(10, i):                        # FIRST: an earlier deep-V cross that would have bought -> not first
        if E9[j] > E20[j] and E9[j - 1] <= E20[j - 1] and c["first_buy_m"] <= M[j] + 1 <= c["last_buy_m"]:
            if deep(j)[0] and ok(j)[0]:
                return False, {"why_not": f"not the first deep V (earlier cross {(M[j] + 30) // 60 + 9}:{(M[j] + 30) % 60:02d})"}
    return True, {"support": info["v_low"], **info}
