#!/usr/bin/env python3
"""Generate video dari foto via Replicate — baca key asli dari TOOLS.md."""
import json, os, re, sys, time, urllib.request, urllib.error

BASE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))  # workspace root

# Baca key asli dari TOOLS.md (jangan pernah di-print)
tools = open(os.path.join(BASE, 'TOOLS.md'), encoding='utf-8').read()
m = re.search(r'Replicate API Key[\s\S]*?Token:\*\*\s*`([^`]+)`', tools)
if not m:
    m = re.search(r'Token:\*\*\s*`([^`]+)`', tools)
if not m:
    print("KEY NOT FOUND")
    sys.exit(1)
KEY = m.group(1).strip()

IMG_URL = "https://files.catbox.moe/q76t4r.jpg"
VERSION = "3f0457e4619daac51203dedb472816fd4af51f3149fa7a9e0b5ffcf1b8172438"  # stable-video-diffusion

body = {
    "version": VERSION,
    "input": {
        "input_image": IMG_URL,
        "video_length": "14_frames_with_svd",
        "sizing_strategy": "maintain_aspect_ratio",
        "motion_bucket_id": 127,
        "frames_per_second": 6
    }
}
req = urllib.request.Request("https://api.replicate.com/v1/predictions",
    data=json.dumps(body).encode(),
    headers={"Authorization": f"Bearer {KEY}", "Content-Type": "application/json"})
try:
    with urllib.request.urlopen(req, timeout=60) as r:
        d = json.loads(r.read())
    print("OK | ID:", d.get("id"), "| STATUS:", d.get("status"))
    open(os.path.join(BASE, "video_orang/prediction_svd.json"), "w").write(json.dumps(d, indent=2))
except urllib.error.HTTPError as e:
    print("HTTP", e.code, e.read().decode()[:400])
