#!/usr/bin/env python3
"""AMARI Scene 1 video — retry otomatis sampai sukses (max 4 percobaan)."""
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).strip()
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

img_url = "https://api.replicate.com/v1/files/NzdjNWQ1YjktYjJjOC00MTJiLTg5NGYtYTQzMDFkZjkwZjMw.png"

PROMPT = ("Cinematic hyper-realistic video: a professional Indonesian presenter in a premium minimalist showroom "
          "holding two UPVC roofing panels (single layer and double layer) side by side, gently turning the panels "
          "to show their profiles, slow smooth camera push-in, Apple keynote product reveal style, light gray studio "
          "background, soft studio lighting, photorealistic Octane render look, 35mm lens, shallow depth of field, "
          "subtle motion, professional advertisement quality. Keep the exact AMARI roofing panel profile unchanged.")


def create_prediction():
    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())
        return pred.get("id"), None
    except urllib.error.HTTPError as e:
        return None, f"{e.code} {e.read().decode()[:300]}"


def poll(pid, max_wait_min=45):
    """Poll sampai selesai. Return (status, output_url_or_error)."""
    deadline = time.time() + max_wait_min * 60
    while time.time() < deadline:
        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
            return "succeeded", url
        if st in ("failed", "canceled"):
            return st, d.get("error")
        if st == "processing":
            print(f"  ...processing ({int(time.time()) % 100000}s)", flush=True)
    return "timeout", None


for attempt in range(1, 5):
    print(f"=== ATTEMPT {attempt}/4 ===", flush=True)
    pid, err = create_prediction()
    if err:
        print(f"CREATE FAIL: {err}", flush=True)
        time.sleep(20)
        continue
    print(f"PREDICTION: {pid}", flush=True)
    with open("video_orang/amari_s1_pred.json", "w") as f:
        json.dump({"pid": pid, "img_url": img_url}, f)
    st, out = poll(pid)
    print(f"RESULT: {st} | {out}", flush=True)
    if st == "succeeded":
        os.system(f'curl -sL "{out}" -o "video_orang/amari_scene1_video.mp4"')
        try:
            sz = os.path.getsize("video_orang/amari_scene1_video.mp4")
            if sz > 1000:
                print(f"✅ SAVED video_orang/amari_scene1_video.mp4 ({sz//1024}KB)", flush=True)
                raise SystemExit(0)
        except Exception:
            pass
        print("download fail, retry...", flush=True)
    time.sleep(30)

print("❌ GAGAL setelah 4 percobaan", flush=True)
