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

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

scenes = [
    {"id": 2, "asset_id": 51540, "prompt": "Lingkaran napas di tengah layar berkembang dan menguncup dengan ritme yang tenang dan berulang. Karakter Surya mengikuti gerakan napas dengan lembut dan peaceful. Smooth breathing animation yang menenangkan.", "output": "/app/working/workspaces/default/balimentari-video-scene2.mp4"},
    {"id": 3, "asset_id": 51541, "prompt": "Karakter Surya dengan ekspresi zen dan tenang. Teks INI CARANYA muncul pelan. Diagram perlahan berubah dari aktif ke tenang dengan arrow animation yang smooth dan menenangkan.", "output": "/app/working/workspaces/default/balimentari-video-scene3.mp4"},
    {"id": 4, "asset_id": 51542, "prompt": "Karakter Surya dengan senyum lebar dan thumbs up. Text MULAI SEKARANG muncul dengan energetic tapi tetap warm. Gentle breathing motion untuk closing yang inspiring dan motivating.", "output": "/app/working/workspaces/default/balimentari-video-scene4.mp4"},
]

for scene in scenes:
    print(f"\n📹 Scene {scene['id']}...")
    
    payload = {
        "prompt": scene["prompt"],
        "mode": "i2v",
        "model": "veo-3.1-lite",
        "aspect_ratio": "portrait",
        "count": 1,
        "start_frame_asset_id": scene["asset_id"]
    }
    
    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🎉 ALL VIDEOS DONE!")
