#!/usr/bin/env python3
"""One-off: SEQ11 call_911 — Seedance 2.0 R2V multishot, 3 segments × 3s.
Uses image refs (DRIVER, BLUE_CAR, SUBURBAN_STREET) — not a start frame.

Run from recoil/pipeline/:
    python3 tools/run_seq11_call911.py
"""
import os, sys, time, json
from pathlib import Path

_HERE = Path(__file__).resolve().parent
_RECOIL_ROOT = _HERE.parent.parent
if str(_RECOIL_ROOT) not in sys.path:
    sys.path.insert(0, str(_RECOIL_ROOT))

from recoil.core.paths import ensure_pipeline_importable
ensure_pipeline_importable()

import fal_client

ENDPOINT  = "bytedance/seedance-2.0/reference-to-video"
PROJECT   = "driver-beware"
PROJ_ROOT = Path(_RECOIL_ROOT).parent / "projects" / PROJECT
PICKS     = PROJ_ROOT / "refs"

driver_ref = PICKS / "characters" / "driver"   / "picks" / "frontal.png"
car_ref    = PICKS / "props"      / "blue_car" / "picks" / "frontal.png"
street_ref = PICKS / "locations"  / "suburban_street" / "establishing.png"

for p in (driver_ref, car_ref, street_ref):
    assert p.exists(), f"Missing ref: {p}"

print("Uploading refs...")
driver_url = fal_client.upload_file(str(driver_ref))
car_url    = fal_client.upload_file(str(car_ref))
street_url = fal_client.upload_file(str(street_ref))
print(f"  @Image1 DRIVER          {driver_url[:60]}")
print(f"  @Image2 BLUE_CAR        {car_url[:60]}")
print(f"  @Image3 SUBURBAN_STREET {street_url[:60]}")

prompt = (
    "[0s-3s] Static close-up, 85mm, on the young driver's right hand. He sits in the "
    "DRIVER'S SEAT (left side of cab, behind the steering wheel) inside the damaged "
    "blue sedan. Blue long-sleeve crewneck pullover, NO hood, NO drawstrings, "
    "shoulder seatbelt strap visible diagonally across his chest. The cracked "
    "windshield with spider-web fracture lines fills the upper background, "
    "soft-blurred. His hand reaches into his jacket pocket, fingers find a "
    "smartphone, and he slowly withdraws it into frame, raising it to chest level. "
    "2D cartoon animation style, clean line weight, warm afternoon light. "
    "[3s-6s] Static extreme close-up, 100mm macro, on the smartphone screen held in "
    "the driver's hand. His thumb taps the dial pad three times in quick succession, "
    "then presses a green call button. The screen brightens and shifts to a calling "
    "interface — soft green glow. Behind the phone, soft-blurred: the cracked "
    "windshield with spider-web fracture lines and the blue cab interior. The "
    "shoulder seatbelt strap visible at the bottom edge of frame. 2D cartoon "
    "animation style, warm light. "
    "[6s-9s] Static medium shot, 50mm, framing the young driver from chest up. He "
    "sits in the DRIVER'S SEAT (left side of cab, behind the steering wheel) inside "
    "the damaged blue sedan parked on a quiet suburban street. Blue long-sleeve "
    "crewneck pullover, NO hood, shoulder seatbelt strap visible diagonally across "
    "his chest. The cracked windshield with spider-web fracture lines fills the "
    "foreground glass between camera and driver. He raises the smartphone to his "
    "right ear, lips moving quietly. His shoulders drop, head nods once slowly. "
    "Through the cracked windshield behind him: pastel suburban houses, wooden power "
    "poles, soft daylight. 2D cartoon animation style, clean line weight, warm "
    "afternoon. Diegetic audio only. No soundtrack."
)

payload = {
    "prompt": prompt,
    "image_urls": [driver_url, car_url, street_url],
    "duration": "9",
    "aspect_ratio": "16:9",
    "resolution": "720p",
    "generate_audio": False,
}

print(f"\nPrompt ({len(prompt.split())} words):")
print(prompt[:200] + "...")

print(f"\nSubmitting to {ENDPOINT} (Seedance 2.0 R2V, 9s multishot, 3 refs)...")
t0 = time.time()

result = fal_client.subscribe(
    ENDPOINT,
    arguments=payload,
    with_logs=True,
)

elapsed = time.time() - t0
print(f"\nDone in {elapsed:.0f}s")

video_url = None
if isinstance(result, dict):
    video_url = (result.get("video") or {}).get("url") or result.get("video_url")
    print("Result keys:", list(result.keys()))

if video_url:
    import urllib.request
    out_dir = PROJ_ROOT / "output" / "video" / "ep_001"
    out_dir.mkdir(parents=True, exist_ok=True)
    out_path = out_dir / "shot_SEQ11_seedance_r2v_take2.mp4"
    print(f"\nDownloading → {out_path}")
    urllib.request.urlretrieve(video_url, out_path)
    print(f"Saved: {out_path}")
else:
    print("No video URL. Result:", json.dumps(result, indent=2)[:500])
