#!/usr/bin/env python3
"""Submit a Sora 2 b-roll via MuAPI (v1 pattern) con gate de costo. No-persona, 9:16."""
import os, sys, time, json, requests

BASE = "https://api.muapi.ai"
KEY = os.environ["MUAPI_KEY"]
H = {"x-api-key": KEY, "Content-Type": "application/json"}

PROMPT = (
    "Cinematic vertical 9:16. A lone business manager seen from behind, shot from over the "
    "shoulder, sitting alone at a desk late at night in a dim office. Multiple glowing screens "
    "and stacks of paper surround a single silhouetted figure; warm amber desk lamp, deep "
    "shadows, the weight of everything resting on one person. Slow subtle push-in, faint "
    "floating dust in the light beam, screens flicker softly. Hands out of frame. No face "
    "visible. Moody, premium, editorial. Ambient motion only, no large movement."
)
MODEL = "openai-sora-2-text-to-video"
OUT = "/home/clawd/playgrounds/ai4m-negocio/brolls/sora.mp4"
MAX_COST = 0.60

payload = {
    "prompt": PROMPT,
    "aspect_ratio": "9:16",
    "duration": 4,
}

def calc_cost():
    try:
        r = requests.post(f"{BASE}/api/v1/models/{MODEL}/estimate-cost",
                          headers=H, json=payload, timeout=60)
        if r.ok:
            return float(r.json().get("cost", 0)), MODEL
        print("  cost calc:", r.status_code, r.text[:200])
    except Exception as e:
        print(f"  cost calc error: {e}")
    return None, None

if __name__ == "__main__":
    cost, tn = calc_cost()
    print(f"COST estimate: ${cost} (task={tn})")
    if cost is None:
        print("No pude calcular costo — abortando para no gastar a ciegas."); sys.exit(2)
    if cost > MAX_COST:
        print(f"ABORT: ${cost} > max ${MAX_COST}"); sys.exit(3)
    if "--submit" not in sys.argv:
        print("Dry-run. Pasa --submit para enviar."); sys.exit(0)

    r = requests.post(f"{BASE}/api/v1/{MODEL}", headers=H, json=payload, timeout=120)
    print("submit:", r.status_code, r.text[:400])
    r.raise_for_status()
    rid = r.json().get("request_id") or r.json().get("data", {}).get("request_id")
    print("request_id:", rid)
    # poll
    for i in range(120):
        time.sleep(10)
        g = requests.get(f"{BASE}/api/v1/predictions/{rid}/result", headers=H, timeout=60)
        if not g.ok:
            print(f"  poll {i}: {g.status_code} {g.text[:200]}"); continue
        d = g.json()
        st = d.get("status") or d.get("data", {}).get("status")
        print(f"  poll {i}: {st}")
        if st in ("completed", "succeeded", "success"):
            outs = d.get("outputs") or d.get("data", {}).get("outputs") or []
            url = outs[0] if outs else (d.get("output") or d.get("data", {}).get("video_url"))
            print("url:", url)
            vid = requests.get(url, timeout=600).content
            open(OUT, "wb").write(vid)
            print(f"OK -> {OUT} ({len(vid)} bytes)"); sys.exit(0)
        if st in ("failed", "error"):
            print("FAILED:", json.dumps(d)[:500]); sys.exit(4)
    print("timeout"); sys.exit(5)
