"""Render video from manifest using the render.ts CLI.

This module provides the render_video() function that shells out to the
existing render.ts CLI to produce MP4 video artifacts from replay manifests.
"""

from __future__ import annotations

import subprocess
from pathlib import Path


def render_video(manifest_path: Path, output_dir: Path, repo_root: Path | None = None) -> Path:
    """Render a video from a manifest using the render.ts CLI.

    Args:
        manifest_path: Path to the manifest JSON file.
        output_dir: Directory where the output MP4 will be written.
        repo_root: Optional repository root path. If not provided, render.ts
                   will derive it from the manifest path.

    Returns:
        Absolute path to the rendered MP4 file.

    Raises:
        RuntimeError: If the renderer exits with non-zero code, produces no
                      output file, or produces an empty file.
    """
    output_path = output_dir / "proof_video.mp4"

    # Resolve render.ts path relative to this module's location
    # This module is at packages/mcp_vm_blackbox/render_video.py
    # render.ts is at packages/mcp_vm_video/render.ts
    render_ts_path = Path(__file__).resolve().parent.parent / "mcp_vm_video" / "render.ts"

    cmd: list[str] = ["npx", "tsx", str(render_ts_path), "--manifest", str(manifest_path), "--output", str(output_path)]

    if repo_root is not None:
        cmd.extend(["--repo-root", str(repo_root)])

    result = subprocess.run(cmd, capture_output=True, text=True, check=False)

    if result.returncode != 0:
        raise RuntimeError(f"Renderer failed (exit {result.returncode}): {result.stderr}")

    if not output_path.exists():
        raise RuntimeError(f"Renderer produced no output at {output_path}")

    if output_path.stat().st_size == 0:
        raise RuntimeError(f"Renderer produced empty output at {output_path}")

    return output_path.resolve()
