#!/usr/bin/env python3
"""
NR Draw Machine · official recording pipeline
=============================================
Replays the draw sequence with the REAL result and exports MP4.
Run AFTER the armed draw, with the actual winning code and the final
entries register, so the film and the record are the same object.

The replay is injected via window.__REPLAY (never a URL parameter),
so the public page cannot be spoofed into showing a fake result.

Usage:
  python3 record_draw.py --code COWYN09 --entries entries.txt
  python3 record_draw.py --code COWYN09 --entries entries.txt --ratio 16x9

entries.txt = one code per line, one line per entry (codes repeat when
a participant holds multiple entries). Must be the final register.

Requires: playwright (chromium installed), ffmpeg on PATH for MP4.
Without ffmpeg the .webm masters are still produced.
"""
import argparse, json, pathlib, shutil, subprocess, sys, time

HTML = pathlib.Path(__file__).parent / "NR_Draw_Machine.html"
SEQUENCE_MS = 16000  # spin ~7s + ink + settle + poster hold

RATIOS = {"9x16": (1080, 1920), "16x9": (1920, 1080)}

def record(code, entries, ratio, outdir):
    from playwright.sync_api import sync_playwright
    w, h = RATIOS[ratio]
    outdir.mkdir(parents=True, exist_ok=True)
    with sync_playwright() as p:
        b = p.chromium.launch()
        ctx = b.new_context(viewport={"width": w, "height": h},
                            device_scale_factor=1,
                            record_video_dir=str(outdir),
                            record_video_size={"width": w, "height": h})
        pg = ctx.new_page()
        pg.add_init_script(f"window.__REPLAY = {json.dumps({'code': code, 'entries': entries})};")
        pg.goto(HTML.resolve().as_uri())
        pg.wait_for_timeout(1200)          # fonts + settle
        pg.click("#runbtn")
        pg.wait_for_timeout(SEQUENCE_MS)   # full sequence + poster hold
        video = pg.video
        ctx.close()
        b.close()
        webm = pathlib.Path(video.path())
    final_webm = outdir / f"NR_Draw_{code}_{ratio}.webm"
    shutil.move(str(webm), final_webm)
    return final_webm

def to_mp4(webm):
    if not shutil.which("ffmpeg"):
        print(f"  ffmpeg not found · master kept as {webm.name}")
        return None
    mp4 = webm.with_suffix(".mp4")
    subprocess.run(["ffmpeg", "-y", "-i", str(webm),
                    "-c:v", "libx264", "-pix_fmt", "yuv420p",
                    "-crf", "18", "-preset", "slow", "-an", str(mp4)],
                   check=True, capture_output=True)
    return mp4

def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--code", required=True, help="the real winning code")
    ap.add_argument("--entries", required=True, help="path to entries.txt, one code per entry")
    ap.add_argument("--ratio", choices=list(RATIOS) + ["both"], default="both")
    ap.add_argument("--outdir", default="draw_films")
    a = ap.parse_args()

    entries = [ln.strip().upper() for ln in open(a.entries) if ln.strip()]
    if a.code.upper() not in entries:
        sys.exit(f"Refusing to record: {a.code} is not in the entries register.")

    ratios = list(RATIOS) if a.ratio == "both" else [a.ratio]
    for r in ratios:
        print(f"Recording {r} …")
        webm = record(a.code.upper(), entries, r, pathlib.Path(a.outdir))
        mp4 = to_mp4(webm)
        print(f"  → {mp4 or webm}")

if __name__ == "__main__":
    main()
