#!/usr/bin/env python3
import json
import sys
import urllib.request
from datetime import datetime, timezone
from pathlib import Path

PROJECT = Path(__file__).resolve().parents[1]
TTS = PROJECT / "log/tts-verification.json"
LAYOUT = PROJECT / "image/layout-manifest.json"
AUDIO = PROJECT / "audio/story-full.wav"
LAYOUT_IMAGE = PROJECT / "image/layout-1920x1080.png"
OUTPUT = PROJECT / "output/footage/footage.mp4"
SUBMISSION = PROJECT / "log/footage-submission.json"
BASE = "http://192.168.1.104:8022"


def main():
    if not TTS.exists() or not LAYOUT.exists() or not AUDIO.exists() or not LAYOUT_IMAGE.exists():
        print("Footage blocked: verified TTS/layout inputs are missing", file=sys.stderr)
        return 1
    tts = json.loads(TTS.read_text(encoding="utf-8"))
    layout = json.loads(LAYOUT.read_text(encoding="utf-8"))
    canon = tts.get("source_canon_sha256")
    if tts.get("verified") is not True or layout.get("verified") is not True or layout.get("visual_qa", {}).get("verified") is not True or layout.get("source_canon_sha256") != canon:
        print("Footage blocked: TTS/layout canon hash mismatch", file=sys.stderr)
        return 1
    if OUTPUT.exists():
        print("Footage blocked: output already exists; inspect existing job instead of overwriting", file=sys.stderr)
        return 1

    with urllib.request.urlopen(BASE + "/health", timeout=20) as response:
        health = json.load(response)
    if health.get("status") != "ok" or health.get("h264_nvenc") is not True:
        print("Footage blocked: GPU endpoint is not healthy", file=sys.stderr)
        return 1

    payload = {
        "layout": str(LAYOUT_IMAGE),
        "footage_dir": "/data/video-pipeline/GacMaiAudio/footage",
        "pattern": "*.mp4", "recursive": True,
        "audio": str(AUDIO), "output": str(OUTPUT),
        "seed": 5005, "overwrite": False,
        "width": 1920, "height": 1080, "fps": 30,
        "center_x": 656, "center_y": 0, "center_width": 608, "center_height": 1080,
        "video_encoder": "h264_nvenc", "preset": "p4", "cq": 21,
    }
    request = urllib.request.Request(
        BASE + "/v1/footage-render-huyenan/jobs",
        data=json.dumps(payload).encode(), headers={"Content-Type": "application/json"}, method="POST",
    )
    with urllib.request.urlopen(request, timeout=30) as response:
        job = json.load(response)
    job_id = job.get("job_id")
    if not job_id or job.get("status") not in {"queued", "running"}:
        print("Footage submission did not return a valid job", file=sys.stderr)
        return 1
    receipt = {
        "version": 1, "verified": False, "source_canon_sha256": canon,
        "job_id": job_id, "status": job.get("status"), "endpoint": BASE,
        "output": str(OUTPUT.relative_to(PROJECT)), "payload": payload,
        "submitted_at": datetime.now(timezone.utc).isoformat(),
    }
    SUBMISSION.parent.mkdir(parents=True, exist_ok=True)
    SUBMISSION.write_text(json.dumps(receipt, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
    print(json.dumps({"job_id": job_id, "status": job.get("status"), "source_canon_sha256": canon, "submission": str(SUBMISSION)}, ensure_ascii=False))
    return 0


if __name__ == "__main__":
    sys.exit(main())
