"""
label_confirmed_all.py -- [2026-10-01] Re-mark every library stock-day with the user-approved
CONFIRMED buy/sell marks (confirmed_marks.py: buy after a swing low held 3+ min and a close
above the low bar's high, not before 9:35; stop under the low; only trades that reached
2x risk and +2%; sell = highest close before the stop). -> data/playbook/day_labels_confirmed.jsonl
"""
import gzip
import json
import sys
from pathlib import Path

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

OUT = Path("/var/www/screener/trade/data/playbook/day_labels_confirmed.jsonl")


def main():
    n = nb = 0
    with open(OUT, "w") as f:
        for p in sorted(LD.BARS.glob("bars_20*.json.gz")):
            d = json.load(gzip.open(p, "rt"))
            for s in d["top30_current"]:
                ref = REF.load(d["date"], s)
                rows = d["symbols"].get(s, {}).get("bars", [])
                if not ref or len(rows) < 200:
                    continue
                B = LD.build(rows, ref)
                if len(B) < 200:
                    continue
                lab = CM.label_confirmed(B)
                f.write(json.dumps({"date": d["date"], "symbol": s, **lab}) + "\n")
                n += 1
                nb += lab["buy"] is not None
            REF._CACHE.clear()
    print(f"{n} stock-days re-marked, {nb} with a confirmed buy mark ({nb / n:.0%}), {n - nb} no trade -> {OUT}")


if __name__ == "__main__":
    main()
