#!/usr/bin/env python3
"""Retry scene 3 visual AMARI — flux-1.1-pro."""
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"

PROMPT = ("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. "
          "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.")

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})
with urllib.request.urlopen(req, timeout=60) as r:
    pred = json.loads(r.read())
pid = pred.get("id")
print(f"Scene 3 retry: {pid}", 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 == "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_v3.png"')
        print("saved video_orang/amari_v3.png" if os.path.getsize("video_orang/amari_v3.png") > 1000 else "download fail")
        break
    if st in ("failed", "canceled"):
        print(f"FAILED: {d.get('error')}", flush=True)
        break
    if i % 3 == 0:
        print(f"  ...{st}", flush=True)
