import json, urllib.request, time

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

print("📹 Scene 4 - CTA (omni-flash)...")

payload = {
    "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. Healing icon with text Practice di story kamu dan tag kami. Cute chibi character Surya orange golden sun with big happy warm smile and thumbs up gesture. @balimentari handle at bottom. Mind Body Soul tagline. Clean modern minimalist wellness content professional inspiring.",
    "mode": "t2v",
    "model": "omni-flash",
    "aspect_ratio": "portrait",
    "count": 1,
    "duration_sec": 6
}

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(15)
        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("/app/working/workspaces/default/balimentari-omni-scene4.mp4", 'wb') as out:
                        out.write(dl.read())
                print("  ✅ Saved!")
                break
            elif s == 'failed':
                print(f"  ❌ FAILED: {status.get('error_message')}")
                break
