import json, urllib.request, urllib.error, time

API_KEY = "vio_sk_vA8llIYm51J3oyXtfevrM92yUBJ8-3IS1sIn6xydF8o"
BASE = "https://api.viostudio.id/v1"

scenes = [
    {
        "id": 2,
        "name": "TEKNIK",
        "prompt": "Instagram Reels portrait 9:16 vertical video. A glowing white circle in center screen breathing expanding and contracting slowly. Cute chibi character Surya orange golden sun child below the circle following the breath rhythm with peaceful zen expression eyes half-closed. Background gradient deep teal to bright teal. Text appears white bold: TARIK 4 detik TAHAN 4 detik BUANG 8 detik. Orange text: TEKNIK NAPAS. Calm breathing animation meditative motion. Professional wellness content soothing hypnotic.",
        "output": "/app/working/workspaces/default/balimentari-omni-scene2.mp4"
    },
    {
        "id": 4,
        "name": "CTA",
        "prompt": "Instagram Reels portrait 9:16 vertical video. Warm cream background. Text COBA SEKARANG appears in deep teal bold at top. Rounded white box with teal border fades in. Phone healing icon with text Practice di story kamu dan tag kami. Cute chibi character Surya orange golden sun at top with big happy warm smile and thumbs up gesture. @balimentari handle at bottom. Mind Body Soul tagline. Clean modern minimalist wellness content professional inspiring.",
        "output": "/app/working/workspaces/default/balimentari-omni-scene4.mp4"
    }
]

for scene in scenes:
    print(f"\n📹 Scene {scene['id']} - {scene['name']} (omni-flash)...")
    
    # omni-flash: duration_sec 4, 6, 8, or 10
    payload = {
        "prompt": scene["prompt"],
        "mode": "t2v",
        "model": "omni-flash",
        "aspect_ratio": "portrait",
        "count": 1,
        "duration_sec": 6  # 6 seconds for omni-flash
    }
    
    req = urllib.request.Request(
        f'{BASE}/videos/generate',
        data=json.dumps(payload).encode(),
        headers={
            'Authorization': f'Bearer {API_KEY}',
            'Content-Type': 'application/json',
            'User-Agent': 'Mozilla/5.0'
        },
        method='POST'
    )
    
    with urllib.request.urlopen(req, timeout=30) as resp:
        result = json.loads(resp.read())
        gen_id = result.get('generation_ids', [0])[0]
        print(f"  Queued! ID: {gen_id}")
        
        while True:
            time.sleep(10)
            status_req = urllib.request.Request(
                f'{BASE}/generations/{gen_id}',
                headers={'Authorization': f'Bearer {API_KEY}', 'User-Agent': 'Mozilla/5.0'}
            )
            with urllib.request.urlopen(status_req, timeout=15) as sr:
                status = json.loads(sr.read())
                s = status.get('status')
                print(f"  Status: {s}")
                
                if s == 'completed':
                    url = status.get('asset_url')
                    print(f"  Downloading...")
                    
                    dl_req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'})
                    with urllib.request.urlopen(dl_req, timeout=60) as dl:
                        with open(scene["output"], 'wb') as out:
                            out.write(dl.read())
                    print(f"  ✅ Saved: {scene['output']}")
                    break
                elif s == 'failed':
                    print(f"  ❌ FAILED: {status.get('error_message')}")
                    break
                time.sleep(8)

print("\n🎉 DONE!")
