"""
book_recorder.py -- [2026-10-11] RECORD ONLY (the user): top-of-book pressure per stock per minute, so the V / entry
studies can test bid-size vs ask-size pressure later (the historical data has no order book).
From every live quote (best bid / best ask with their sizes) it keeps, per symbol and minute:
  n quotes, mean bid size, mean ask size, imbalance = (bid size - ask size) / (bid size + ask size) over the minute,
  mean spread %, how often the best bid moved up / down and the best ask moved up / down, and the last quote.
Output: data/book/<date>.jsonl (one row per symbol-minute, written when the next minute's first quote arrives).
Never raises into the stream; never touches trading. Sizes are as Alpaca sends them (SIP: round lots).
"""
import json
import logging
import threading
from pathlib import Path
from zoneinfo import ZoneInfo

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


class BookRecorder:
    def __init__(self, cfg=None):
        self.cfg = cfg or {}
        self.cur = {}            # sym -> accumulator for the current minute
        self.lock = threading.Lock()
        self.errors = 0

    def on_quote(self, sym, ts, bid, ask, bsz, asz):
        try:
            t = ts.astimezone(ET)
            key = t.strftime("%Y-%m-%d %H:%M")
            with self.lock:
                a = self.cur.get(sym)
                if a is not None and a["minute"] != key:
                    self._flush(sym, a)
                    a = None
                if a is None:
                    a = {"minute": key, "n": 0, "bsz": 0.0, "asz": 0.0, "spr": 0.0, "bid_up": 0, "bid_dn": 0, "ask_up": 0,
                         "ask_dn": 0, "pb": (self.cur.get(sym) or {}).get("last_bid"), "pa": (self.cur.get(sym) or {}).get("last_ask")}
                    if a["pb"] is None and sym in self.cur:
                        a["pb"], a["pa"] = self.cur[sym].get("last_bid"), self.cur[sym].get("last_ask")
                    self.cur[sym] = a
                a["n"] += 1; a["bsz"] += bsz; a["asz"] += asz
                mid = (bid + ask) / 2
                a["spr"] += (ask - bid) / mid * 100 if mid else 0
                pb, pa = a.get("last_bid", a["pb"]), a.get("last_ask", a["pa"])
                if pb is not None:
                    a["bid_up"] += bid > pb; a["bid_dn"] += bid < pb
                if pa is not None:
                    a["ask_up"] += ask > pa; a["ask_dn"] += ask < pa
                a.update(last_bid=bid, last_ask=ask, last_bsz=bsz, last_asz=asz)
        except Exception as e:
            self.errors += 1
            if self.errors <= 5:
                log.warning(f"[BOOK] {sym}: {e}")

    def _flush(self, sym, a):
        n = a["n"]
        if not n:
            return
        tot = a["bsz"] + a["asz"]
        row = {"sym": sym, "minute": a["minute"][11:], "n": n, "bid_size": round(a["bsz"] / n, 2), "ask_size": round(a["asz"] / n, 2),
               "imbalance": round((a["bsz"] - a["asz"]) / tot, 4) if tot else None, "spread_pct": round(a["spr"] / n, 4),
               "bid_up": a["bid_up"], "bid_dn": a["bid_dn"], "ask_up": a["ask_up"], "ask_dn": a["ask_dn"],
               "last": [a.get("last_bid"), a.get("last_bsz"), a.get("last_ask"), a.get("last_asz")]}
        p = BASE / "data" / "book" / f"{a['minute'][:10]}.jsonl"
        p.parent.mkdir(parents=True, exist_ok=True)
        with open(p, "a") as fh:
            fh.write(json.dumps(row) + "\n")
