"""
massive_flow_tick.py -- [2026-10-05] TICK-RULE buy/sell flow per minute from Massive trades (the user, 10/5:
flow everywhere by the tick rule, so the library, the new years and the live Star bot all match).
Tick rule: price above the previous trade = buy, below = sell, same = the previous trade's side.
Part 1: the current 2-year library (reports/open_window/bars/bars_<day>.json.gz, top 30 per day).
Later: any list of stock-days (--list file.json: [[day, symbol], ...]) from the 10-year bars.
  output: reports/open_window/flow_tick/<day>/<SYM>.json  {"buy": [390], "sell": [390], "trades": n}
Resumable; 6 stocks in parallel; never runs 9:10-16:05 on weekdays. Raw trades are not kept.
    python3 massive_flow_tick.py [--list stockdays.json]
"""
import gzip
import json
import sys
import time
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime
from pathlib import Path
from zoneinfo import ZoneInfo

HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
from massive_trial import m_trades, tick_flow

ET = ZoneInfo("America/New_York")
OUT = HERE / "flow_tick"


def market_hours():
    t = datetime.now(ET)
    return t.weekday() < 5 and (9, 10) <= (t.hour, t.minute) < (16, 5)


def one(day, sym):
    f = OUT / day / f"{sym}.json"
    if f.exists():
        return 0
    tr = m_trades(sym, day)
    buy, sell = tick_flow(tr)
    f.parent.mkdir(parents=True, exist_ok=True)
    tmp = f.with_suffix(".tmp")
    tmp.write_text(json.dumps({"buy": [round(x) for x in buy], "sell": [round(x) for x in sell], "trades": len(tr)}))
    tmp.rename(f)
    return 1


def main():
    if "--list" in sys.argv:
        todo = [tuple(x) for x in json.load(open(sys.argv[sys.argv.index("--list") + 1]))]
    else:
        todo = []
        for p in sorted((HERE / "bars").glob("bars_20*.json.gz"), reverse=True):
            d = json.load(gzip.open(p, "rt"))
            todo += [(d["date"], s) for s in d["top30_current"]]
    todo = [x for x in todo if not (OUT / x[0] / f"{x[1]}.json").exists()]
    print(f"{len(todo)} stock-days to do", flush=True)
    t0, done = time.time(), 0
    for i in range(0, len(todo), 30):
        if market_hours():
            print("stopped: market hours", flush=True); return
        chunk = todo[i:i + 30]
        with ThreadPoolExecutor(3) as ex:          # [2026-10-07] was 6: ~600 MB, memory pressure 10/6
            res = list(ex.map(lambda x: _safe(*x), chunk))
        done += sum(res)
        print(f"{chunk[-1][0]}: {done} done [{(time.time() - t0) / 60:.0f} min]", flush=True)
    print("FLOW_TICK_DONE", flush=True)


def _safe(day, sym):
    try:
        return one(day, sym)
    except Exception as e:
        print(f"{day} {sym} failed: {e}", flush=True)
        return 0


if __name__ == "__main__":
    main()
