"""
group_watch.py -- [2026-10-09] LOG ONLY (the user). For every scanner candidate, at each checkpoint (9:45, 10:00,
10:15, 10:30, 11:00, 11:30) it puts the stock in its GROUP (reports/open_window/group_tree.py: readable filters
fitted on 2021-2023, checked on 2024-2026) and logs it. The first time a stock lands in a WINNER group it logs a
GROUP BUY SIGNAL at the checkpoint price. It NEVER places, changes or blocks an order.
Output: data/group_watch/<date>.jsonl (one row per stock per checkpoint) + "[GROUP]" lines in the bot log.
Later: reports/playbook/group_compare.py compares the signals with the bot's own entries and the day's right entry.
The features MUST stay identical to reports/open_window/group_build.py features() (same formulas, same order).
"""
import json
import logging
import math
from datetime import datetime
from pathlib import Path
from zoneinfo import ZoneInfo

ET = ZoneInfo("America/New_York")
BASE = Path(__file__).resolve().parent
log = logging.getLogger("trade_bot.group_watch")


def _features(O, H, L, C, V, t, atrp, gap, pmv, prev_vol):
    P = C[-1]; hi, lo = max(H), min(L); cv = sum(V)
    vw = sum((h + l + c) / 3 * v for h, l, c, v in zip(H, L, C, V)) / cv if cv else P
    w0 = max(0, t - 15)
    path = sum(abs(C[i] - C[i - 1]) for i in range(w0 + 1, t))
    base = C[max(0, t - 16)] if t > 15 else O
    ret = (P / O - 1) * 100
    style = "none"
    hit = [i for i in range(t) if H[i] >= O * 1.02]
    if hit:
        k = hit[0]; lb = (min(L[:k + 1]) / O - 1) * 100
        p2 = sum(abs(C[i] - C[i - 1]) for i in range(1, k + 1))
        eff = (C[k] - O) / p2 if p2 > 0 else 1.0
        bs = (max(H[k - 35:k - 5]) - min(L[k - 35:k - 5])) / O * 100 if k >= 35 else 99
        style = ("deep V" if lb <= -3 else "dip, then up" if lb <= -1 else "straight" if k < 15 else
                 "late move" if k >= 270 else "base break" if bs <= 1.0 else "slow grind" if k >= 60 and eff >= 0.25 else "choppy")
    nan = float("nan")
    f = {"t": t, "gap": gap, "atrp": atrp, "pmv_log": math.log10(max(pmv or 0, 0) + 1), "ret": ret,
         "hi": (hi / O - 1) * 100, "lo": (lo / O - 1) * 100, "ret_atr": ret / atrp if atrp and atrp == atrp else nan,
         "vwap": (P / vw - 1) * 100,
         "vol_rel_log": math.log10(cv / prev_vol) if prev_vol and cv > 0 else nan, "r15": (P / base - 1) * 100,
         "eff15": (C[-1] - C[w0]) / path if path > 0 else 0.0, "rng15": (max(H[w0:]) - min(L[w0:])) / O * 100,
         "pos": (P - lo) / (hi - lo) if hi > lo else 0.5, "off_hi": (P / hi - 1) * 100}
    for s in ("none", "straight", "dip, then up", "deep V", "base break", "slow grind", "late move", "choppy"):
        f[f"st_{s}"] = 1.0 if style == s else 0.0
    return f, style, P


class GroupWatch:
    def __init__(self, cfg: dict):
        self.cfg = cfg or {}
        m = json.load(open(BASE / self.cfg.get("model", "data/group_model.json")))
        self.tree, self.checks = m["tree"], m["checks"]
        self.done = {}            # symbol -> set of checkpoints logged
        self.signaled = {}        # symbol -> signal row
        self.day = None

    def _leaf(self, f):
        n = self.tree
        while not n.get("leaf"):
            v = f.get(n["f"], float("nan"))
            n = n["L"] if ((v < n["q"]) if v == v else n["nan_left"]) else n["R"]
        return n

    def _write(self, row):
        p = BASE / "data" / "group_watch" / f"{self.day}.jsonl"
        p.parent.mkdir(parents=True, exist_ok=True)
        with open(p, "a") as fh:
            fh.write(json.dumps(row, default=str) + "\n")

    def tick(self, now_et, candidates, get_bars, daily_atr, prev_vol):
        """candidates: scanner rows; get_bars(sym) -> CLOSED minute bars; daily_atr / prev_vol: sym -> value."""
        day = now_et.date().isoformat()
        if day != self.day:
            self.day, self.done, self.signaled = day, {}, {}
        now_m = (now_et.hour - 9) * 60 + now_et.minute - 30
        due = [t for t in self.checks if t <= now_m]
        if not due:
            return
        for c in candidates:
            s = c["symbol"]
            todo = [t for t in due if t not in self.done.setdefault(s, set())]
            if not todo:
                continue
            try:
                self._eval(s, c, todo, get_bars(s), daily_atr.get(s), prev_vol.get(s))
            except Exception as e:
                self.done[s].update(todo)
                log.warning(f"[GROUP] {s}: {e}")

    def _eval(self, s, c, todo, bars, atr, pv):
        by = {}
        for b in bars:
            t = b["t"].astimezone(ET) if hasattr(b["t"], "astimezone") else b["t"]
            m = (t.hour - 9) * 60 + t.minute - 30
            if 0 <= m < 390:
                by[m] = b
        if 0 not in by:
            self.done[s].update(todo)                    # no official 9:30 bar -> cannot match the training data
            log.info(f"[GROUP] {s}: no 9:30 bar, skipped"); return
        mt = self.cfg.get("max_late_minutes", 10)        # a checkpoint is judged only close to its own time
        m_metrics = c.get("metrics", {})
        pc = m_metrics.get("previous_close")
        O = float(by[0]["o"])
        atrp = atr / pc * 100 if atr and pc else float("nan")
        if atrp == atrp and atrp > 25:
            atrp = float("nan")
        gap = (O / pc - 1) * 100 if pc else float("nan")
        for t in todo:
            if max(by) < t - 1:
                continue                                  # bar t-1 not closed yet; retry next tick
            self.done[s].add(t)
            now_m = max(by)
            if now_m - (t - 1) > mt and t != todo[-1]:
                continue                                  # stock added by a late rescan: judge only the latest checkpoint
            H, L, C, V = [], [], [], []
            last = None
            for m in range(t):
                b = by.get(m)
                if b is None:                             # no trade that minute: carry the last close (as in training)
                    b = {"h": last, "l": last, "c": last, "v": 0.0}
                H.append(float(b["h"])); L.append(float(b["l"])); C.append(float(b["c"])); V.append(float(b["v"]))
                last = C[-1]
            f, style, P = _features(O, H, L, C, V, t, atrp, gap, m_metrics.get("premarket_volume"), pv)
            leaf = self._leaf(f)
            hm = f"{9 + (30 + t) // 60}:{(30 + t) % 60:02d}"
            row = {"day": self.day, "sym": s, "check": hm, "t": t, "price": P, "group": leaf["gid"], "label": leaf["label"],
                   "style": style, "desc": leaf["desc"], "test_mean": leaf.get("test_mean"),
                   "f": {k: (round(v, 4) if isinstance(v, float) and v == v else v) for k, v in f.items() if not k.startswith("st_")}}
            if leaf["label"] == "WINNER" and s not in self.signaled:
                row["signal"] = "BUY"
                self.signaled[s] = row
                log.info(f"[GROUP] BUY SIGNAL (log only) {s} @ {P:.2f} at {hm}: {leaf['gid']} {leaf['label']} "
                         f"(test {leaf.get('test_mean') or 0:+.2f}%/trade) style={style} | {leaf['desc']}")
            else:
                log.info(f"[GROUP] {s} {hm} @ {P:.2f}: {leaf['gid']} {leaf['label']} style={style}")
            self._write(row)
