"""
ev3.py -- [2026-10-23] ENTRY VERSION 3 (EV3) for the trade bot, the user's decision: "retire the trade bot for now and replace it
with EV3". Live from Monday 10/26 (paper). config.json -> smart_engine.entry_mode "ev3" + section "ev3". Revert: entry_mode "v2".
ENTRIES = the user's chart setups (built from the practice charts, tested on 2 years with the give-back exit):
  R3   opening push -> first pullback holds -> turn      ONLY stocks with daily ATR 6-10% (2y: +0.153%/trade, y1 +0.167 y2 +0.142)
  R1A  fast double bottom after a flush                  (2y: +0.076%/trade, +0.067 / +0.085)
  R4   runner's second leg after the base                (2y: +0.129%/trade, +0.002 / +0.201)
  R1B  undercut & reclaim after a flush (PEPG deep V)    (rare: 24 trades in 2 years, mixed -- included for data)
  R7 is left out (to be improved); R5 / R8 / R9 / R1 / R2 / R6 lost with every exit.
  Each setup is checked once per FINISHED minute on the stream's bars and per-minute buy/sell flow (the same code the 2-year
  test ran: r1a_setup / r1b_setup / r3_setup / r4_setup), with its own cool-down per stock.
STOP = under the setup's own support (support x (1 - stop_buf)), clamped to stop_min_pct..stop_max_pct under the price.
EXIT = the 1/4 GIVE-BACK: nothing but the stop until the peak since the buy is >= arm_pct above the buy; then sell when the
  price falls to peak - giveback x (peak - buy) while it is falling (price under the last finished close). 15:55 by the bot.
E1 (2026-10-23, the user's sell block from JOBY 10/23/24 + DERM 11/5/24; tested as "E2et" on the 833 2-year EV3 buys:
  give-back alone -0.052%/trade -> +0.096%, y1 +0.227 / y2 -0.009): when the give-back fires, E1 OVERRIDES it (holds) while
    buyers are in control: 5-min buy share >= 50% AND NOT the last 2 finished minutes both "seller minutes" (1-min buy share
    < 40% on volume >= 0.5x the 15-bar average -- a lone small print is not a seller minute), OR
    the dip is noise: peak - last finished close < 2 x the mean 1-min range of the last 15 bars.
  Re-checked every finished minute; when E1 stops holding and the give-back is still true -> sell. Never overrides the stop;
  never holds once the price is at/under the buy price. Reads finished bars + per-minute flow only.
Pure logic + per-symbol state; no orders (monitor.py / position_manager.py place them).
"""
import logging
from datetime import datetime, timezone
from zoneinfo import ZoneInfo

import r1a_setup
import r1b_setup
import r3_setup
import r4_setup

log = logging.getLogger("trade_bot.ev3")
ET = ZoneInfo("America/New_York")
MODS = {"R1A": r1a_setup, "R1B": r1b_setup, "R3": r3_setup, "R4": r4_setup}
DEFAULTS = {
    "setups": {"R1A": {}, "R1B": {}, "R4": {}, "R3": {"atr_min": 6.0, "atr_max": 10.0}},
    "order": ["R1A", "R1B", "R4", "R3"],
    "arm_pct": 1.0, "giveback": 0.25, "stop_buf": 0.002, "stop_min_pct": 0.5, "stop_max_pct": 4.0,
    "last_entry_minute": 360,
    "e1": {"enabled": True, "bs5_min": 0.50, "seller_bs": 0.40, "thin_x": 0.5, "noise_k": 2.0},
}


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


class EV3:
    def __init__(self, cfg=None):
        c = {**DEFAULTS, **(cfg or {})}
        c["setups"] = {**DEFAULTS["setups"], **((cfg or {}).get("setups") or {})}
        c["e1"] = {**DEFAULTS["e1"], **((cfg or {}).get("e1") or {})}
        self.c = c
        self._last_m = {}         # symbol -> last finished minute checked
        self._last_trig = {}      # (symbol, setup) -> minute of the last trigger (cool-down)
        self._peak = {}           # symbol -> {"entry_time", "peak"}
        self._e1_last = {}        # symbol -> (minute, hold?) last E1 log

    # ------------------------------------------------------------------ entries
    def entry_check(self, symbol, bars, min_flow, ref):
        """bars: the stream's bars (last one forming); min_flow: {minute bucket datetime: [buy, sell]};
        ref: reference.load(). -> None or {"setup", "info", "stop", "price", "m"} once per finished minute."""
        if not ref or not ref.get("atr14") or not ref.get("prev_close"):
            return None
        done = [b for b in bars[:-1] if 0 <= minute_of(b["t"]) < 390]
        if len(done) < 5:
            return None
        m = minute_of(done[-1]["t"])
        if self._last_m.get(symbol) == m or m >= self.c["last_entry_minute"]:
            return None
        self._last_m[symbol] = m
        fb, fs = [0.0] * 390, [0.0] * 390
        for t, v in min_flow:
            k = minute_of(t)
            if 0 <= k < 390:
                fb[k] += v[0]; fs[k] += v[1]
        flow = {"buy": fb, "sell": fs}
        atrp = ref["atr14"] / ref["prev_close"] * 100
        for name in self.c["order"]:
            sc = self.c["setups"].get(name)
            if sc is None or sc.get("enabled") is False:
                continue
            if "atr_min" in sc and atrp < sc["atr_min"]:
                continue
            if "atr_max" in sc and atrp >= sc["atr_max"]:
                continue
            mod = MODS[name]
            if m - self._last_trig.get((symbol, name), -9999) < mod.DEFAULTS.get("cooldown", 15):
                continue
            try:
                ok, info = mod.check(done, flow, ref, m)
            except Exception as e:
                log.warning(f"[EV3] {symbol} {name} check failed: {e}")
                continue
            if ok:
                self._last_trig[(symbol, name)] = m
                P = done[-1]["c"]
                sup = info.get("stop") or (info.get("support") or P * 0.99) * (1 - self.c["stop_buf"])
                stop = min(max(sup, P * (1 - self.c["stop_max_pct"] / 100)), P * (1 - self.c["stop_min_pct"] / 100))
                return {"setup": name, "info": info, "stop": round(stop, 4), "price": P, "m": m, "atr": round(atrp, 1)}
        return None

    # ------------------------------------------------------------------ exits
    def e1_hold(self, bars_done, min_flow, peak):
        """E1: (hold?, why) from the FINISHED regular-session bars + per-minute flow."""
        e = self.c["e1"]
        done = [b for b in bars_done if 0 <= minute_of(b["t"]) < 390]
        if not e.get("enabled") or len(done) < 3:
            return False, "E1 off"
        fb, fs = [0.0] * 390, [0.0] * 390
        for t, v in min_flow:
            k_ = minute_of(t)
            if 0 <= k_ < 390:
                fb[k_] += v[0]; fs[k_] += v[1]
        def bs(m, n):
            B = sum(fb[max(0, m - n + 1):m + 1]); S = sum(fs[max(0, m - n + 1):m + 1])
            return B / (B + S) if B + S else 0.5
        def avgv(i):
            w = done[max(0, i - 15):i]
            return sum(x["v"] for x in w) / len(w) if w else 0
        def seller(i):
            return bs(minute_of(done[i]["t"]), 1) < e["seller_bs"] and done[i]["v"] >= e["thin_x"] * avgv(i)
        k = len(done) - 1; m = minute_of(done[k]["t"])
        b5 = bs(m, 5); two = seller(k) and seller(k - 1)
        rng = sum(x["h"] - x["l"] for x in done[-15:]) / len(done[-15:])
        dip = peak - done[k]["c"]
        if b5 >= e["bs5_min"] and not two:
            return True, f"buyers in control: 5-min buy share {b5:.0%}, no 2 seller minutes in a row"
        if dip < e["noise_k"] * rng:
            return True, f"noise: dip {dip:.4g} < {e['noise_k']:g} x 1-min range {rng:.4g}"
        return False, (f"buyers gone: 5-min buy share {b5:.0%}" + (", 2 seller minutes in a row" if two else "")
                       + f"; dip {dip:.4g} >= {e['noise_k']:g} x range {rng:.4g}")

    def exit_check(self, symbol, pos, bars, price, min_flow=()):
        """-> (should_exit, reason, is_risk_exit). pos: position_manager position (entry_price, stop_price, entry_time)."""
        entry, stop = pos["entry_price"], pos.get("stop_price") or pos["entry_price"] * 0.99
        st = self._peak.get(symbol)
        if not st or st.get("entry_time") != pos.get("entry_time"):
            st = self._peak[symbol] = {"entry_time": pos.get("entry_time"), "peak": entry}
        et = datetime.fromisoformat(pos["entry_time"]) if pos.get("entry_time") else None
        done = bars[:-1]
        since = [b for b in done if et is None or b["t"] >= et.replace(second=0, microsecond=0)]
        if since:
            st["peak"] = max(st["peak"], max(b["h"] for b in since))
        if price <= stop:
            return True, f"EV3 stop: {price:.4g} <= {stop:.4g} (under the {pos.get('ev3_setup', 'setup')} support)", True
        gain = st["peak"] - entry
        if gain >= entry * self.c["arm_pct"] / 100 and done:
            lvl = st["peak"] - self.c["giveback"] * gain
            if price <= lvl and price < done[-1]["c"]:
                gb = (f"EV3 give-back: peak {st['peak']:.4g} (+{gain / entry * 100:.2f}%), "
                      f"price {price:.4g} <= {lvl:.4g} (1/{round(1 / self.c['giveback'])} given back)")
                if price > entry:
                    try:
                        h, why = self.e1_hold(done, min_flow, st["peak"])
                    except Exception as ex:
                        h, why = False, f"E1 failed ({ex})"
                    mk = minute_of(done[-1]["t"])
                    if h:
                        if self._e1_last.get(symbol) != (mk, True):
                            self._e1_last[symbol] = (mk, True)
                            log.info(f"[EV3] E1 HOLD {symbol} @ {price}: give-back level {lvl:.4g} touched, held -- {why}")
                        return False, "", False
                    if self._e1_last.get(symbol, (None, False))[1]:
                        gb = gb.replace("EV3 give-back", "EV3 give-back after E1 released") + f" | {why}"
                    self._e1_last.pop(symbol, None)
                return True, gb, False
        st["peak"] = max(st["peak"], price)
        return False, "", False

    def forget(self, symbol):
        self._peak.pop(symbol, None)
        self._e1_last.pop(symbol, None)
