"""
stock_board.py -- [2026-10-28] The user's STOCK BOARD: follows one stock from the open, every finished 1-min bar, and keeps:
  RESISTANCE  starts at the premarket high; the first swing high of the day (e.g. the gap-up run) REPLACES it; every later swing
              high is AVERAGED in (resistance = mean of the day's swing highs).               [user 10/28: "averaged"]
  SUPPORT     the first dip's swing low; every later swing low is AVERAGED in. Before any swing: the day's low so far.
  RANGE       resistance - support ($, % of price, x daily ATR) and the price's position in it (0 = support, 1 = resistance).
  VOLUME ACC  last 3 bars' average volume / the bars before them (the 15 before; from 6 bars on, all before -> buys from ~9:36).
  BUY / SELL  share of buyers over 3 and 15 minutes (flow), and whether each rose vs 1 minute ago.
  VWAP        price vs VWAP and VWAP's 5-minute slope.
  PATTERN     opening_patterns.Recognizer (the 40 patterns): a BULLISH pattern ARMS the board for 15 minutes ("buy candidate");
              a bearish / neutral one = "keep watching" (a bearish one cancels the arm).
  BUY SIGNAL  [user 10/28 "yes"] armed AND rise confirmed: close above the trigger (the high of the bar that confirmed the pattern),
              3-min buy share above the 15-min, and volume accelerating (>= 1.0). The buy is at the next bar's open.
Entries only, record / study only: it never places an order. Swings, patterns and levels use finished bars (no look-ahead).
"""
from opening_patterns import Recognizer, CATALOG, BIAS_UP, BIAS_DOWN


class Board:
    ARM_MIN = 15

    def __init__(self, prev_close, atr_dollar, open_price, pm_high=None):
        self.R = Recognizer(prev_close, atr_dollar, open_price)
        self.pm_high = pm_high; self.hi_list = []; self.lo_list = []; self.n_piv = 0
        self.fb, self.fs = [], []; self.vw_hist = []; self.armed = None; self.state = "watching"; self.rows = []; self.buys = []

    def _share(self, n, back=0):
        b = self.fb[-n - back:len(self.fb) - back] if back else self.fb[-n:]; s = self.fs[-n - back:len(self.fs) - back] if back else self.fs[-n:]
        return sum(b) / (sum(b) + sum(s)) if sum(b) + sum(s) else 0.5

    def update(self, bar, t, buy_vol, sell_vol):
        """bar: finished 1-min bar (h,l,c,v); buy_vol / sell_vol: that minute's flow. -> the board row (dict); row['buy'] True = buy signal"""
        R = self.R; new = R.update(bar, t); self.fb.append(buy_vol); self.fs.append(sell_vol); self.vw_hist.append(R.vwap)
        for k, p, tp in R.piv[self.n_piv:]:
            if k == "H": self.hi_list.append(p)
            else: self.lo_list.append(p)
        self.n_piv = len(R.piv)
        c = R.C[-1]
        res = sum(self.hi_list) / len(self.hi_list) if self.hi_list else max(self.pm_high or 0, max(R.H))
        sup = sum(self.lo_list) / len(self.lo_list) if self.lo_list else min(R.L)
        rng = max(res - sup, 1e-9)
        # [2026-10-28, user: 'shorter'] from 6 bars on: last 3 bars vs ALL the bars before them (up to the 15 before) -- buys from ~9:36
        V = R.V; prev = V[-18:-3] if len(V) >= 18 else V[:-3]
        vacc = (sum(V[-3:]) / 3) / (sum(prev) / len(prev)) if len(V) >= 6 and sum(prev) else None
        s3, s15 = self._share(3), self._share(15); s3p, s15p = self._share(3, 1), self._share(15, 1)
        vws = (R.vwap / self.vw_hist[-6] - 1) * 100 if len(self.vw_hist) >= 6 else 0.0
        for pid in new:                                  # patterns confirmed on this bar
            if pid in BIAS_UP:
                self.armed = dict(pid=pid, t=t, trigger=bar["h"]); self.state = f"BUY CANDIDATE (#{pid})"
            elif pid in BIAS_DOWN:
                self.armed = None; self.state = f"keep watching (bearish #{pid})"
            elif self.armed is None:
                self.state = f"keep watching (#{pid})"
        buy = False
        if self.armed and t - self.armed["t"] > self.ARM_MIN:
            self.armed = None; self.state = "watching (candidate expired)"
        elif self.armed and t > self.armed["t"] and c > self.armed["trigger"] and s3 > s15 and vacc is not None and vacc >= 1.0:
            buy = True; self.buys.append(dict(t=t, pid=self.armed["pid"], armed_t=self.armed["t"])); self.state = f"BUY SIGNAL (#{self.armed['pid']} confirmed)"
            self.armed = None
        row = dict(t=t, c=c, res=round(res, 4), sup=round(sup, 4), range_pct=round(rng / c * 100, 2), range_atr=round(rng / R.u, 2),
                   pos=round((c - sup) / rng, 2), vacc=round(vacc, 2) if vacc else None, s3=round(s3, 3), s15=round(s15, 3),
                   s3_up=s3 > s3p, s15_up=s15 > s15p, vwap=round(R.vwap, 4), vs_vwap=round((c / R.vwap - 1) * 100, 2), vwap_slope=round(vws, 3),
                   new=new, state=self.state, buy=buy)
        self.rows.append(row); return row
