"""star_live_lists.py -- [2026-10-24] the user: simulate EV3 on the Star bot's REAL days. From the Star bot's saved scans
(premarket/data/candidates/<day>_scanner[_HHMM].json: the 9:28 list + every rescan, top 50) -> star_lists_live/<day>.json in the
star_lists format {"pre": [...], "rescans": {minute since 9:30: [...]}, "ref", "union"}; ref from pm_history (atr, prev_close,
prev_high) + the previous pm_history day's low."""
import gzip, json, re
from pathlib import Path
OW = Path("/var/www/screener/trade/reports/open_window"); HERE = Path(__file__).resolve().parent
C = Path("/var/www/screener/premarket/data/candidates"); OUT = HERE / "star_lists_live"; OUT.mkdir(exist_ok=True)
days = sorted({f.name[:10] for f in C.glob("2026-*_scanner*.json")})
pms = sorted(f.name[:10] for f in (OW / "pm_history").glob("20*.json.gz"))
for day in days:
    pre = [c["symbol"] for c in json.load(open(C / f"{day}_scanner.json"))]
    resc = {}
    for f in sorted(C.glob(f"{day}_scanner_*.json")):
        hh, mm = int(f.stem[-4:-2]), int(f.stem[-2:]); t = (hh - 9) * 60 + mm - 30
        resc[t] = [c["symbol"] for c in json.load(open(f))]
    union = sorted(set(pre) | {s for L in resc.values() for s in L})
    rows = {r["s"]: r for r in json.load(gzip.open(OW / "pm_history" / f"{day}.json.gz", "rt"))["rows"]} if day in pms else {}
    prev = pms[pms.index(day) - 1] if day in pms else None
    prows = {r["s"]: r for r in json.load(gzip.open(OW / "pm_history" / f"{prev}.json.gz", "rt"))["rows"]} if prev else {}
    ref = {s: {"atr14": (rows.get(s) or {}).get("atr"), "prev_close": (rows.get(s) or {}).get("prev_close"),
               "prev_high": (rows.get(s) or {}).get("prev_high"), "prev_low": (prows.get(s) or {}).get("l")} for s in union}
    (OUT / f"{day}.json").write_text(json.dumps({"date": day, "pre": pre, "rescans": resc, "ref": ref, "union": union}))
    print(day, len(pre), len(resc), "rescans", len(union), "stocks", sum(1 for s in union if ref[s]["atr14"]), "with pm_history ref")
