"""
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.
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,
}


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 {})}
        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"}

    # ------------------------------------------------------------------ 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 exit_check(self, symbol, pos, bars, price):
        """-> (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:
            lvl = st["peak"] - self.c["giveback"] * gain
            falling = bool(done) and price < done[-1]["c"]
            if price <= lvl and falling:
                return True, (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)"), False
        st["peak"] = max(st["peak"], price)
        return False, "", False

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