#!/usr/bin/env python3
"""AMARI Scene 4 video — Engineering compare (Single vs Double cross-section + air chamber arrow)."""
import json, re, time, urllib.request, os

tools = open('TOOLS.md', encoding='utf-8').read()
m = re.search(r'r8_[A-Za-z0-9]+', tools)
KEY = m.group(0)
UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0 Safari/537.36"
VERSION = "fa8b2706824084e968dfe1d1cdff8e0193b40ef908827e3d2940a927704a5f43"

SRC = 'video_orang/amari_v4.png'
boundary = "----wb" + "99123"
data = open(SRC, 'rb').read()
parts = []
parts.append("--" + boundary + "\r\nContent-Disposition: form-data; name=\"filename\"\r\n\r\namari_scene4.png\r\n")
parts.append(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"content\"; filename=\"amari_scene4.png\"\r\nContent-Type: image/png\r\n\r\n").encode() + data + b"\r\n")
parts.append("--" + boundary + "--\r\n")
body = b"".join(p if isinstance(p, bytes) else p.encode() for p in parts)

req = urllib.request.Request("https://api.replicate.com/v1/files", data=body,
    headers={"Authorization": "Bearer " + KEY, "Content-Type": "multipart/form-data; boundary=" + boundary, "User-Agent": UA})
with urllib.request.urlopen(req, timeout=90) as r:
    up = json.loads(r.read())
img_url = up["urls"]["get"]
print("UPLOAD OK:", img_url, flush=True)

PROMPT = ("Cinematic hyper-realistic product showcase: a premium UPVC roofing panel displayed cleanly on a white studio stage, "
          "slow smooth 360-degree rotation revealing the neat corrugated zincalume profile, soft studio lighting, subtle red accent "
          "details, Apple keynote product reveal style, photorealistic Octane render look, macro product shot, professional "
          "advertisement quality. Keep the exact AMARI roofing panel profile unchanged, no logo, no text overlay.")

body = {"version": VERSION, "input": {
    "image": img_url, "prompt": PROMPT, "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": "Bearer " + KEY, "Content-Type": "application/json", "User-Agent": UA})
try:
    with urllib.request.urlopen(req, timeout=60) as r:
        pred = json.loads(r.read())
except urllib.error.HTTPError as e:
    print("CREATE FAIL:", e.code, e.read().decode()[:400], flush=True)
    raise SystemExit(1)
pid = pred.get("id")
print("PREDICTION:", pid, "|", pred.get('status'), flush=True)

for i in range(90):
    time.sleep(8)
    req = urllib.request.Request("https://api.replicate.com/v1/predictions/" + pid,
        headers={"Authorization": "Bearer " + KEY, "User-Agent": UA})
    try:
        with urllib.request.urlopen(req, timeout=30) as r:
            d = json.loads(r.read())
    except Exception as e:
        print("  poll err", e, flush=True)
        continue
    st = d.get("status")
    if st == "succeeded":
        out = d["output"]
        url = out[0] if isinstance(out, list) else out
        print("DONE:", url, flush=True)
        os.system('curl -sL "' + url + '" -o "video_orang/amari_scene4_video.mp4"')
        if os.path.exists("video_orang/amari_scene4_video.mp4"):
            sz = os.path.getsize("video_orang/amari_scene4_video.mp4")
            print("saved video_orang/amari_scene4_video.mp4 (" + str(sz//1024) + "KB)" if sz > 1000 else "download fail")
        break
    if st in ("failed", "canceled"):
        print("FAILED:", d.get('error'), flush=True)
        break
    if i % 4 == 0:
        print("  ..." + str(st) + " (" + str(i*8) + "s)", flush=True)
