#!/usr/bin/env python3
"""Synthetic Sprint 6I-B browser fixture; no patient media or data."""
from __future__ import annotations
import io, os, sqlite3, subprocess, sys
from pathlib import Path
from PIL import Image
import pillow_heif

ROOT=Path(__file__).resolve().parents[2]; HEALTH=ROOT/"scripts"/"health"
sys.path[:0]=[str(HEALTH),str(ROOT/"tests")]
from fixtures.dashboard_v5_fixture import build_dashboard_v5_fixture
from dashboard_v5.capture_media import quarantine_bytes
import health_dashboard_action_worker as worker
from health_dashboard_v5 import main as render_main


def heic() -> bytes:
    pillow_heif.register_heif_opener(); output=io.BytesIO(); Image.new("RGB",(160,100),(43,104,166)).save(output,format="HEIF",quality=80); return output.getvalue()


def hevc(path: Path) -> bytes:
    subprocess.run(["ffmpeg","-nostdin","-v","error","-f","lavfi","-i","color=c=blue:s=160x100:d=1","-c:v","libx265","-preset","ultrafast","-pix_fmt","yuv420p","-an","-threads","1","-y",str(path)],check=True,timeout=60)
    return path.read_bytes()


def build(root: Path) -> None:
    root.mkdir(parents=True,exist_ok=True); database=root/"health.db"; build_dashboard_v5_fixture(database)
    quarantine=root/"capture-quarantine"; media=root/"capture-media"
    worker.DASHBOARD_DB=database; worker.CAPTURE_QUARANTINE=quarantine; worker.CAPTURE_MEDIA=media; worker.DASHBOARD_V5_FILE=None
    photo=quarantine_bytes(quarantine,heic()); video=quarantine_bytes(quarantine,hevc(root/"synthetic.mov"))
    payload={"version":1,"action":"capture_entry","capture_type":"event","request_version":1,"idempotency_key":"b"*32,"occurred_at":"2026-07-18T12:00","ended_at":"","data":{"title":"Synthetisches Ereignis","note":"Nur synthetische Testdaten","category":"other","intensity":"unknown"},"attachments":[photo,video],"corrects_entry_id":None,"withdraws_entry_id":None}
    worker.apply_capture_action(payload)
    token=root/"api-token"; token.write_text("browser-synthetic-token-6ib-1234567890\n"); os.chmod(token,0o600)
    old=list(sys.argv);sys.argv=["health_dashboard_v5.py","--db",str(database),"--output",str(root/"dashboard-v5.html"),"--today","2026-07-19","--generated-at","2026-07-19T12:00:00+02:00","--health-record-6e"]
    try: render_main()
    finally: sys.argv=old

if __name__=="__main__": build(Path(sys.argv[1]).resolve())
