#!/usr/bin/env python3
"""AMARI Scene 3 video — upload visual ke Replicate, generate seedance-2.5 i2v, download."""
import json, re, time, urllib.request, os

tools = open('TOOLS.md', encoding='utf-8').read()
m = re.search(r'Replicate API Key[\s\S]*?Token:\*\*\s*`([^`]+)`', tools)
KEY = m.group(1)
UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0 Safari/537.36"
VERSION = "fa8b2706824084e968dfe1d1cdff8e0193b40ef908827e3d2940a927704a5f43"  # seedance-2.5

# 1. Upload visual scene 3 (Double Layer render + air chamber)
SRC = 'video_orang/amari_v3.png'
boundary = "----wb" + "99123"
data = open(SRC, 'rb').read()
parts = []
parts.append(f"--{boundary}\r\nContent-Disposition: form-data; name=\"filename\"\r\n\r\namari_scene3.png\r\n")
parts.append(f"--{boundary}\r\nContent-Disposition: form-data; name=\"content\"; filename=\"amari_scene3.png\"\r\nContent-Type: image/png\r\n\r\n".encode() + data + b"\r\n")
parts.append(f"--{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": f"Bearer {KEY}", "Content-Type": f"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)

# 2. Generate video seedance i2v — Scene 3: Double Layer + air chamber cross-section
PROMPT = ("Cinematic hyper-realistic product visualization: a double layer UPVC roofing panel rendered large on screen, "
          "slow smooth rotation revealing the layered construction and the internal hollow air chamber cross-section, "
          "thin red accent lines highlighting the double-layer walls and the sealed air cavity for insulation, "
          "Apple keynote engineering reveal style, light gray studio background, soft studio lighting, photorealistic "
          "Octane render look, macro product shot, subtle motion, professional advertisement quality. Keep the exact "
          "AMARI double layer 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": f"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(f"CREATE FAIL: {e.code} {e.read().decode()[:400]}", flush=True)
    raise SystemExit(1)
pid = pred.get("id")
print(f"PREDICTION: {pid} | {pred.get('status')}", flush=True)

# 3. Poll
for i in range(90):
    time.sleep(8)
    req = urllib.request.Request(f"https://api.replicate.com/v1/predictions/{pid}",
        headers={"Authorization": f"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(f"  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(f"DONE: {url}", flush=True)
        os.system(f'curl -sL "{url}" -o "video_orang/amari_scene3_video.mp4"')
        if os.path.exists("video_orang/amari_scene3_video.mp4"):
            sz = os.path.getsize("video_orang/amari_scene3_video.mp4")
            print(f"saved video_orang/amari_scene3_video.mp4 ({sz//1024}KB)" if sz > 1000 else "download fail")
        break
    if st in ("failed", "canceled"):
        print(f"FAILED: {d.get('error')}", flush=True)
        break
    if i % 4 == 0:
        print(f"  ...{st} ({i*8}s)", flush=True)
