#!/usr/bin/env python3
"""Generate ulang 9 visual AMARI — flux-1.1-pro, NO TEXT (teks di-overlay PIL)."""
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"

NO_TEXT = (" Absolutely NO text, NO words, NO letters, NO numbers, NO labels, NO watermark, NO logo text — "
           "pure visual only, clean uncluttered composition with generous negative space.")

FRAMES = {
 1: ("Hyper-realistic premium 9:16 vertical product visualization: professional Indonesian presenter in a premium "
     "minimalist showroom holding two UPVC roofing panels side by side (single layer and double layer), modern Apple "
     "keynote style, light gray studio background, white negative space at top for headline. Photorealistic Octane "
     "render, Unreal Engine 5, ray tracing, 8K texture, PBR materials, 35mm lens product shot. Use the AMARI roofing "
     "panel exactly as reference: same wave profile, rib thickness, side lock, chamber layout, extrusion shape. "
     "Do NOT redesign the roof. No cartoon, no anime, no plastic look." + NO_TEXT),
 2: ("Hyper-realistic premium 9:16 vertical product visualization: large single layer UPVC roofing panel render "
     "with visible cross section profile, clean white studio background, product centered with space around for labels, "
     "engineering visualization style, photorealistic Octane render, ray tracing, PBR materials. Use the AMARI roofing "
     "panel exactly as reference: same wave profile, rib thickness, side lock, chamber layout, extrusion shape. "
     "Do NOT redesign the roof. No cartoon, no anime, no plastic look." + NO_TEXT),
 3: ("Hyper-realistic premium 9:16 vertical product visualization: large double layer UPVC roofing panel render "
     "with enclosed air chamber visible in cross section, clean white studio background, product centered with space "
     "around for labels, engineering visualization style, photorealistic Octane render, ray tracing, PBR materials. "
     "Use the AMARI roofing panel exactly as reference: same wave profile, rib thickness, side lock, chamber layout, "
     "extrusion shape. Do NOT redesign the roof. No cartoon, no anime, no plastic look." + NO_TEXT),
 4: ("Hyper-realistic premium 9:16 vertical engineering blueprint visualization: enlarged cross sections of UPVC "
     "roofing panel, single layer section on top and double layer section below, engineering blueprint style with "
     "technical grid lines, arrows pointing at the air chamber gap, precise engineering drawing, dark blueprint "
     "background with white and red technical annotations style, professional CAD look. Use the AMARI roofing panel "
     "exactly as reference: same wave profile, rib thickness, side lock, chamber layout, extrusion shape." + NO_TEXT),
 5: ("Hyper-realistic premium 9:16 vertical infographic visualization: split screen comparison, left side hot "
     "red-orange scene with bright sun and heat waves representing single layer roof, right side cool blue scene "
     "with comfortable temperature representing double layer roof, clean modern split composition, white space for "
     "labels, photorealistic Octane render, ray tracing, PBR materials, AMARI red #C62828 and blue accents." + NO_TEXT),
 6: ("Hyper-realistic premium 9:16 vertical comparison visualization: heavy rain storm on left side over a "
     "conventional roof with loud dramatic sound wave graphics, right side cozy quiet modern house interior with "
     "happy family silhouette under a double layer roof with small calm sound waves, split screen, photorealistic "
     "Octane render, ray tracing, PBR materials, cinematic lighting." + NO_TEXT),
 7: ("Hyper-realistic premium 9:16 vertical product visualization: two UPVC roofing panels side by side (single "
     "layer and double layer) on clean white background, product comparison composition with even spacing and "
     "negative space for a comparison table, minimalist corporate style, photorealistic Octane render, ray tracing, "
     "PBR materials, AMARI red #C62828 accent. Use the AMARI roofing panel exactly as reference." + NO_TEXT),
 8: ("Hyper-realistic premium 9:16 vertical decision visualization: two columns composition, left column single "
     "layer roofing panel with industrial outdoor context (warehouse workshop), right column double layer roofing "
     "panel with comfortable modern home office context, clean white background, split decision layout with space "
     "for text, photorealistic Octane render, ray tracing, PBR materials, AMARI red #C62828 accent." + NO_TEXT),
 9: ("Hyper-realistic premium 9:16 vertical closing visualization: beautiful modern minimalist house at golden "
     "hour sunset, warm cinematic light, large clean area in center for logo placement, premium architectural "
     "photography, photorealistic Octane render, Unreal Engine 5, ray tracing, 8K texture, PBR materials, "
     "35mm lens, shallow depth of field." + NO_TEXT),
}

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_v{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")
