#!/usr/bin/env python3
import json
import subprocess
import sys
from pathlib import Path

PROJECT = Path(__file__).resolve().parents[1]
VALIDATOR = PROJECT / "script" / "validate-production-v3.py"
REPORT = PROJECT / "log" / "v3" / "production-verification.json"
FINAL = PROJECT / "output" / "v3" / "final.mp4"
UPLOAD = PROJECT / "output" / "v3" / "final-upload.mp4"
TRANSCODE_REPORT = PROJECT / "log" / "v3" / "upload-transcode.json"
METADATA = PROJECT / "output" / "v3" / "info.txt"
OLD_BLOCK = PROJECT / "DO_NOT_PUBLISH_V2.json"

result = subprocess.run([sys.executable, str(VALIDATOR)], cwd=PROJECT)
if result.returncode != 0:
    print("Publish blocked: production v3 verification failed", file=sys.stderr)
    raise SystemExit(result.returncode)
report = json.loads(REPORT.read_text(encoding="utf-8"))
if report.get("verified") is not True or report.get("status") != "passed":
    print("Publish blocked: verification report is not passed", file=sys.stderr)
    raise SystemExit(1)
if not FINAL.exists() or not UPLOAD.exists() or not TRANSCODE_REPORT.exists() or not METADATA.exists() or not OLD_BLOCK.exists():
    print("Publish blocked: required v3 final/upload copy/transcode receipt/metadata/v2 block missing", file=sys.stderr)
    raise SystemExit(1)
transcode = json.loads(TRANSCODE_REPORT.read_text(encoding="utf-8"))
server = transcode.get("server_verification", {})
if (
    transcode.get("verified") is not True
    or transcode.get("status") != "completed"
    or transcode.get("source_canon_sha256") != report.get("source_canon_sha256")
    or server.get("verified") is not True
    or server.get("under_one_gb") is not True
    or int(server.get("output_bytes", 0)) != UPLOAD.stat().st_size
    or UPLOAD.stat().st_size >= 1_000_000_000
):
    print("Publish blocked: upload copy is not verified below 1,000,000,000 bytes for current canon", file=sys.stderr)
    raise SystemExit(1)
print(json.dumps({
    "publish_ready": True,
    "source_canon_sha256": report["source_canon_sha256"],
    "master_video": str(FINAL),
    "video": str(UPLOAD),
    "video_bytes": UPLOAD.stat().st_size,
    "transcode_job_id": transcode["job_id"],
    "metadata": str(METADATA),
    "forbidden_video": str(PROJECT / "output" / "final.mp4"),
}, ensure_ascii=False))
