#!/usr/bin/env python3
"""Generate frame storyboard AMARI — flux-1.1-pro + image_prompt referensi."""
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).strip()
UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0 Safari/537.36"

REF_URL = "https://api.replicate.com/v1/files/YmY5ZTkwMDgtMjY4My00YzNjLTk3N2QtYmQ5YWJhNTMyNDVm.jpg"

VERSION = "609793a667ed94b210242837d3c3c9fc9a64ae93685f15d75002ba0ed9a97f2b"

FRAMES = {
 1: ("Hyper-realistic premium storyboard frame 9:16 for AMARI ROOF UPVC roofing advertisement. "
     "Scene 1 OPENING: A professional Indonesian presenter in a premium showroom holding two UPVC roofing panels "
     "(single layer and double layer) side by side, modern minimal Apple-style setting, light gray background, "
     "clean white space. Bold red typography title reads 'Single Layer vs Double Layer' and subtitle "
     "'Which one is right for your building?'. Photorealistic, Octane render, Unreal Engine 5, ray tracing, "
     "8K texture, PBR materials, architectural visualization, 35mm lens, product shot. White and light gray palette "
     "with AMARI red #C62828 accents. Thin red border frame around the panel. Small red scene number '01'. "
     "Minimalist premium corporate style."),
}

def gen(n, prompt):
    body = {"version": VERSION, "input": {
        "prompt": prompt,
        "image_prompt": REF_URL,
        "aspect_ratio": "9:16",
        "prompt_upsampling": True,
        "output_format": "png",
        "output_quality": 95,
        "safety_tolerance": 2,
    }}
    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 scene {n}: {e.code} {e.read().decode()[:300]}")
        return None
    pid = pred.get("id")
    print(f"Scene {n}: prediction {pid} | {pred.get('status')}", flush=True)
    for i in range(60):
        time.sleep(8)
        req = urllib.request.Request(f"https://api.replicate.com/v1/predictions/{pid}",
            headers={"Authorization": f"Bearer {KEY}", "User-Agent": UA})
        with urllib.request.urlopen(req, timeout=30) as r:
            d = json.loads(r.read())
        st = d.get("status")
        if st in ("succeeded", "failed", "canceled"):
            if st == "succeeded":
                print(f"  DONE: {d['output']}")
                return d["output"]
            print(f"  FAILED: {d.get('error')}")
            return None
    print(f"  TIMEOUT scene {n}")
    return None

out = gen(1, FRAMES[1])
if out:
    import urllib.request as u
    u.urlretrieve(out[0], "video_orang/amari_frame1.png")
    print("saved video_orang/amari_frame1.png")
