#!/usr/bin/env python3
"""Upload scene2 ke Replicate lalu generate video seedance-2.5."""
import json, re, time, urllib.request

tools = open('TOOLS.md', encoding='utf-8').read()
m = re.search(r'Replicate API Key[\s\S]*?Token:\*\*\s*`([^`]+)`', tools)
KEY = m.group(1)

# 1. Upload scene2.png
boundary = "----wb" + "77777"
parts = []
parts.append(f"--{boundary}\r\nContent-Disposition: form-data; name=\"filename\"\r\n\r\nscene2.png\r\n")
data = open('video_orang/scene2.png', 'rb').read()
parts.append(f"--{boundary}\r\nContent-Disposition: form-data; name=\"content\"; filename=\"scene2.png\"\r\nContent-Type: image/png\r\n\r\n".encode() + data + b"\r\n")
parts.append(f"--{boundary}--\r\n".encode())
body_bytes = b"".join(p.encode() if isinstance(p, str) else p for p in parts)

req = urllib.request.Request("https://api.replicate.com/v1/files",
    data=body_bytes,
    headers={"Authorization": f"Bearer {KEY}", "Content-Type": f"multipart/form-data; boundary={boundary}"})
with urllib.request.urlopen(req, timeout=60) as r:
    d = json.loads(r.read())
file_url = d["urls"]["get"]
print("UPLOAD OK:", d.get("id"))

# 2. Generate seedance-2.5 — scene 2 INTRODUCE produk atap
body = {
    "version": "fa8b2706824084e968dfe1d1cdff8e0193b40ef908827e3d2940a927704a5f43",
    "input": {
        "image": file_url,
        "prompt": ("Hyper-realistic cinematic video: Indonesian man in red safety helmet holding a "
                   "corrugated zincalume metal roofing sheet, silver-grey color with trapezoidal wave profile, "
                   "introducing the roofing product, natural hand movement, realistic skin texture, "
                   "workshop background, professional lighting, shallow depth of field, no logo, no text overlay, "
                   "smooth natural motion, 4K quality"),
        "duration": 5,
        "resolution": "720p",
        "generate_audio": False,
        "watermark": False
    }
}
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:
        pred = json.loads(r.read())
    print("PREDICTION:", pred.get("id"), "|", pred.get("status"))
    open("video_orang/pred_scene2.json", "w").write(json.dumps(pred, indent=2))
except urllib.error.HTTPError as e:
    print("HTTP", e.code, e.read().decode()[:400])
