"""
lib_v3.py -- [2026-10-04] Playbook matching library v3 = lib_v2's 6 channels + BUY/SELL FLOW (the user,
2026-10-04, for the Star bot in /var/www/screener/premarket):
  P, W, X, SPY, IWM, GAP   exactly as lib_v2.day_arrays
  FL   net buying over the last 15 minutes: (buy - sell) / (buy + sell), -1..+1 (0 when no trades)
       from reports/open_window/flow/<day>/<SYM>.json (per-minute buy/sell volume, quote rule with
       tick-rule fallback; build_flows.flows). Days without a flow file are left OUT of v3.
Library cache: data/playbook/library_v3.npz (F, C, H, L, keys)
"""
import gzip
import json
import sys
from pathlib import Path

import numpy as np

HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE)); sys.path.insert(0, "/var/www/screener/trade")
import lib_v2 as L2
import reference as REF

FLOW = Path("/var/www/screener/trade/reports/open_window/flow")
CACHE = Path("/var/www/screener/trade/data/playbook/library_v3.npz")
N, FLOW_WIN = 390, 15


def flow_channel(buy, sell, win=FLOW_WIN):
    """per minute: (buy - sell) / (buy + sell) over the last `win` minutes (incl. that minute)"""
    b = np.cumsum(np.asarray(buy, float)); s = np.cumsum(np.asarray(sell, float))
    bw = b - np.concatenate([np.zeros(win), b[:-win]]); sw = s - np.concatenate([np.zeros(win), s[:-win]])
    tot = bw + sw
    return np.where(tot > 0, (bw - sw) / np.maximum(tot, 1e-9), 0.0).astype(np.float32)


def day_arrays(rows, ref, day, bench=None, flow=None):
    a = L2.day_arrays(rows, ref, day, bench)
    if a is None or flow is None:
        return None
    a["F"] = np.concatenate([a["F"], flow_channel(flow["buy"], flow["sell"])[:, None]], axis=1)
    return a


class Lib:
    def __init__(self):
        if CACHE.exists():
            z = np.load(CACHE, allow_pickle=True)
            self.F, self.C, self.H, self.L, self.keys = z["F"], z["C"], z["H"], z["L"], list(z["keys"])
        else:
            F, C, H, L, keys = [], [], [], [], []
            for p in sorted(L2.BARS.glob("bars_20*.json.gz")):
                d = json.load(gzip.open(p, "rt")); day = d["date"]
                bench = L2.bench_paths(day)
                for s in d["top30_current"]:
                    fp = FLOW / day / f"{s}.json"
                    ref = REF.load(day, s)
                    if not ref or not fp.exists():
                        continue
                    a = day_arrays(d["symbols"][s]["bars"], ref, day, bench, json.loads(fp.read_text()))
                    if a is None:
                        continue
                    F.append(a["F"]); C.append(a["C"].astype(np.float32)); H.append(a["H"].astype(np.float32))
                    L.append(a["L"].astype(np.float32)); keys.append(f"{day}|{s}")
                REF._CACHE.clear()
            self.F, self.C, self.H, self.L, self.keys = np.array(F), np.array(C), np.array(H), np.array(L), keys
            np.savez(CACHE, F=self.F, C=self.C, H=self.H, L=self.L, keys=np.array(keys))
        self.dates = np.array([k.split("|")[0] for k in self.keys])


if __name__ == "__main__":
    lib = Lib()
    print(len(lib.keys), "stock-days", lib.F.shape, "days", len(set(lib.dates)))
