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

PROJECT = Path(__file__).resolve().parents[1]
PROMOTION = PROJECT / "story/promotion-receipt.json"
PLAN = PROJECT / "script/production-plan.json"


def verified_promotion():
    if not PROMOTION.exists() or not PLAN.exists():
        return False
    try:
        receipt = json.loads(PROMOTION.read_text())
        plan = json.loads(PLAN.read_text())
    except Exception:
        return False
    return receipt.get("verified") is True and plan.get("status") == "story_promoted_ready_for_tts" and receipt.get("promoted_canon_sha256") == plan.get("canon_sha256")


def run(script):
    return subprocess.run([sys.executable, "-B", str(PROJECT / "script" / script)], cwd=PROJECT)


def main():
    deadline = time.time() + 3 * 60 * 60
    while time.time() < deadline and not verified_promotion():
        time.sleep(20)
    if not verified_promotion():
        print("Media watcher timed out before verified promotion", file=sys.stderr)
        return 2
    for script in ("build-image-brief.py", "build-metadata.py"):
        result = run(script)
        if result.returncode:
            return result.returncode
    tts = subprocess.Popen([sys.executable, "-B", str(PROJECT / "script/render-tts.py")], cwd=PROJECT)
    images = subprocess.Popen([sys.executable, "-B", str(PROJECT / "script/generate-images.py")], cwd=PROJECT)
    tts_code = tts.wait()
    image_code = images.wait()
    if tts_code or image_code:
        print(json.dumps({"tts_exit": tts_code, "images_exit": image_code}), file=sys.stderr)
        return 1
    print(json.dumps({"tts": "completed", "images": "completed"}))
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
