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

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

headers = {
    "Authorization": f"Bearer {API_KEY}",
    "Content-Type": "application/json",
    "User-Agent": "Mozilla/5.0"
}

# Generate video from image (i2v mode)
payload = {
    "prompt": "The chibi sunshine character Surya gently blinks and breathes. The text LO PANIC? OVERTHINKING? STRESSED? glows softly. Smooth, calm breathing motion. Professional Instagram wellness content. Subtle animation, not too much movement.",
    "mode": "i2v",
    "model": "veo-3.1-lite",
    "aspect_ratio": "portrait",
    "count": 1,
    "start_frame_asset_id": ASSET_ID
}

req = urllib.request.Request(
    f"{BASE}/videos/generate",
    data=json.dumps(payload).encode(),
    headers=headers,
    method="POST"
)

try:
    with urllib.request.urlopen(req, timeout=30) as resp:
        result = json.loads(resp.read())
        print(json.dumps(result, indent=2))
        gen_id = result["generation_ids"][0]
        print(f"\n📹 Generation ID: {gen_id}")
        
        # Poll for result
        print("\n⏳ Waiting for video to complete...")
        for i in range(40):
            time.sleep(8)
            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())
                print(f"[{i+1}] Status: {status.get('status')}")
                
                if status["status"] == "completed":
                    print(f"\n✅ VIDEO DONE!")
                    print(f"URL: {status.get('asset_url')}")
                    break
                elif status["status"] == "failed":
                    print(f"\n❌ FAILED: {status.get('error_message')}")
                    break
        
except urllib.error.HTTPError as e:
    print('HTTP Error:', e.code, e.read().decode())
except Exception as e:
    print('Error:', str(e))
