#!/usr/bin/env python3
"""Generate 9 frame storyboard AMARI ROOF — flux-1.1-pro + image_prompt referensi."""
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"
REF_URL = "https://api.replicate.com/v1/files/YmY5ZTkwMDgtMjY4My00YzNjLTk3N2QtYmQ5YWJhNTMyNDVm.jpg"
VERSION = "609793a667ed94b210242837d3c3c9fc9a64ae93685f15d75002ba0ed9a97f2b"

BASE = ("Hyper-realistic premium 9:16 vertical storyboard frame for AMARI ROOF UPVC roofing advertisement. "
        "White background, thin red border frame, red scene number top-left, clean minimal typography, "
        "Apple keynote style, photorealistic Octane render, Unreal Engine 5, ray tracing, 8K texture, PBR materials, "
        "architectural visualization, AMARI red #C62828 accents on white and light gray palette. "
        "Use the AMARI roofing panel product exactly as reference: keep the exact wave profile, rib thickness, "
        "side lock, chamber layout and extrusion shape. Do NOT redesign the roof. No cartoon, no anime, no plastic look.")

FRAMES = {
 2: BASE + (" Scene 2 SINGLE LAYER: large product render of the single layer UPVC roofing panel, cross section visible, "
            "engineering callout labels: '1 UPVC Layer', 'Lightweight', 'Affordable', 'Easy installation'. "
            "Application icons row: Garage, Workshop, Canopy, Warehouse, Farm. Red scene number '02'."),
 3: BASE + (" Scene 3 DOUBLE LAYER: large product render of the double layer UPVC roofing panel with enclosed air chamber "
            "visible in cross section, engineering callout labels: 'Double Layer', 'Air Chamber', 'Better insulation', 'Quieter'. "
            "Application icons row: House, Factory, School, Commercial Building. Red scene number '03'."),
 4: BASE + (" Scene 4 ENGINEERING COMPARISON: single layer cross section on top, double layer cross section below, "
            "enlarged engineering blueprint style, arrows pointing at the air chamber, blueprints with red annotations, "
            "precise engineering drawing. Red scene number '04'."),
 5: BASE + (" Scene 5 HEAT INSULATION: split screen comparison, left side labeled 'Single Layer' with temperature '38 C' "
            "and red hot sun icon, right side labeled 'Double Layer' with temperature '29 C' and cool blue icon, "
            "animated heat flow arrows, sunlight icon, clean infographic. Red scene number '05'."),
 6: BASE + (" Scene 6 RAIN SOUND: heavy rain storm, left side 'Conventional roof' with loud sound wave icons, "
            "right side 'AMARI Double Layer' quiet cozy interior with happy family silhouette, sound waves small. "
            "Red scene number '06'."),
 7: BASE + (" Scene 7 COMPARISON TABLE: clean minimal comparison table 'Single Layer vs Double Layer', rows: Price, Weight, "
            "Heat Insulation, Noise Reduction, Applications, Comfort, checkmarks and values, infographic style. "
            "Red scene number '07'."),
 8: BASE + (" Scene 8 WHICH SHOULD YOU CHOOSE: two columns, left 'Single Layer' if: Budget priority, Outdoor building, "
            "Warehouse, Workshop; right 'Double Layer' if: House, Office, Factory, School, Maximum comfort. "
            "Minimal decision infographic with red and gray accents. Red scene number '08'."),
 9: BASE + (" Scene 9 CLOSING: beautiful modern minimalist house at golden hour sunset, large AMARI logo centered, "
            "tagline 'Cooler. Quieter. Stronger.' in bold typography, premium minimalist ending. Red scene number '09'."),
}

def gen(n, prompt):
    body = {"version": VERSION, "input": {
        "prompt": prompt,
        "image_prompt": REF_URL,
        "aspect_ratio": "9:16",
        "prompt_upsampling": True,
        "output_format": "png",
        "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]}", flush=True)
        return None
    pid = pred.get("id")
    print(f"Scene {n}: {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})
        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)
            fn = f"video_orang/amari_frame{n}.png"
            os.system(f'curl -sL "{url}" -o "{fn}"')
            if os.path.exists(fn) and os.path.getsize(fn) > 1000:
                return fn
            print("  download fail", flush=True)
            return None
        if st in ("failed", "canceled"):
            print(f"  FAILED: {d.get('error')}", flush=True)
            return None
    print(f"  TIMEOUT scene {n}", flush=True)
    return None

for n in sorted(FRAMES.keys()):
    fn = gen(n, FRAMES[n])
    if fn:
        print(f"  saved {fn}", flush=True)
    else:
        print(f"  !! scene {n} gagal", flush=True)
    time.sleep(3)
print("SELESAI")
