#!/usr/bin/env python3
"""Single-take 10s continuous render of SH03 scene (Pass 2 content).

Combines the 4 segment prompts from Pass 2 into one continuous prompt
and submits as a single 10s shot via StepRunner.execute_video().
Uses Kling V3 (fal.ai) for the render.
"""
import sys
from pathlib import Path

# Bootstrap path: RECOIL_ROOT first (so `from core.X` resolves to recoil/core/),
# then PIPELINE_ROOT via the canonical helper.
PIPELINE_ROOT = Path(__file__).parent.parent
RECOIL_ROOT = PIPELINE_ROOT.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()

from recoil.execution.execution_store import ExecutionStore
from recoil.execution.step_runner import StepRunner
from recoil.execution.step_types import ProjectPaths
from recoil.pipeline.core.dispatch import dispatch
from recoil.pipeline.core.dispatch_context import DispatchContext
from recoil.pipeline.core.cost import read_cost_from_result

PROJECT = "tartarus"
EPISODE = 1
MODEL = "kling-o3"
DURATION = 10
SHOT_ID = "EP001_SH03"

# Start frame from Pass 2
START_FRAME = Path("/Users/joeturnerlin/Dropbox/CLAUDE_DATA/recoil/projects/tartarus/output/previs/ep_001/shot_036_take6_81821.png")

# Combined prompt — all 4 segments as continuous action
PROMPT = (
    "Continuous single-take, no cuts. "
    "MS: Torch standing at corridor wall in dim futuristic spaceship corridor, "
    "right hand resting on hip, left hand touching wall, head turned back over "
    "right shoulder toward corridor behind her — sharp pivot, scanning the darkness, "
    "tense posture. She checks the exits, one collapsed bulkhead visible in the distance. "
    "Camera drifts closer as she raises her left wrist to check the amber-glowing debt counter, "
    "numbers ticking up, harsh shadows on skin. "
    "She looks back over her right shoulder scanning the corridor, eyes calculating, "
    "jaw setting — the gambler's pause before committing. "
    "Slight head tilt down, deadpan expression, a small shrug — unbothered, "
    "flat pragmatism as she studies a corroded panel on the bulkhead wall."
)

def main():
    paths = ProjectPaths.for_episode(PROJECT, EPISODE)
    store = ExecutionStore(project=PROJECT)
    runner = StepRunner(store=store, paths=paths)

    # Ensure shot exists in store (may already exist from prior renders)
    try:
        shot = store.get_shot(SHOT_ID)
        if shot:
            # Reset to a state that allows video_submitted transition
            current = shot.get("status", "")
            if current not in ("video_pending", "previs_approved", "video_failed"):
                store.update_shot(SHOT_ID, status="video_pending")
    except Exception:
        pass

    print(f"Submitting single-take 10s render of {SHOT_ID}")
    print(f"  Model: {MODEL}")
    print(f"  Duration: {DURATION}s")
    print(f"  Start frame: {START_FRAME}")
    print(f"  Output dir: {paths.video_dir}")
    print()

    ctx = DispatchContext(
        caller_id="single_take",
        step_runner=runner,
        project=PROJECT,
        episode=EPISODE,
    )
    receipt = dispatch(
        "video_i2v",
        {
            "shot_id": SHOT_ID,
            "prompt": PROMPT,
            "model": MODEL,
            "start_frame": START_FRAME,
            "duration": DURATION,
            "aspect_ratio": "9:16",
        },
        context=ctx,
    )
    result = receipt.run_result

    if result.success:
        cost_usd = read_cost_from_result(result)
        take_index = result.metadata.get("take_index")
        print(f"\n[OK] Single-take render complete!")
        print(f"  Output: {result.output_path}")
        print(f"  Cost: ${cost_usd:.3f}")
        print(f"  Take: {take_index}")
    else:
        print(f"\n[FAIL] {result.error}")


if __name__ == "__main__":
    main()
