#!/usr/bin/env python3
"""Export Edit Decision List (EDL) or FCPXML for editorial handoff.

Usage:
    python tools/export_edl.py --episode 1 --format edl
    python tools/export_edl.py --episode 1 --format fcpxml

Generates a timeline file that Premiere Pro / DaVinci Resolve can import
to auto-assemble a rough cut from generated video clips.

Phase A skeleton — full implementation in Phase C.
"""

import argparse
import json
import sys
from pathlib import Path

from recoil.core.paths import PIPELINE_ROOT, ProjectPaths


def _load_log(episode: int, project: str = None) -> dict | None:
    """Load log.json for an episode."""
    log_path = ProjectPaths.for_project(project).episode_prep_dir(episode) / "log.json"
    if not log_path.exists():
        return None
    return json.loads(log_path.read_text(encoding="utf-8"))


def build_edl(episode: int, output_dir: Path | None = None) -> Path:
    """Generate CMX 3600 EDL from log.json.

    Reads log.json for shot order, durations, and file paths.
    Outputs: ep_001.edl

    Args:
        episode: Episode number.
        output_dir: Override output directory.

    Returns:
        Path to the generated EDL file.
    """
    # Full implementation in Phase C
    # Will read log.json + video clip metadata to build:
    # - CMX 3600 EDL with proper timecode
    # - Source reel names from clip filenames
    # - V (video) and A (audio) edit events
    raise NotImplementedError(
        "EDL export — full implementation in Phase C. "
        "Requires video clips with duration metadata in log.json."
    )


def build_fcpxml(episode: int, output_dir: Path | None = None) -> Path:
    """Generate FCPXML 1.11 from log.json.

    Same source data as EDL, but in XML format compatible with
    Final Cut Pro and DaVinci Resolve.

    Args:
        episode: Episode number.
        output_dir: Override output directory.

    Returns:
        Path to the generated FCPXML file.
    """
    # Full implementation in Phase C
    # Will generate FCPXML 1.11 with:
    # - <project> element with timeline
    # - <asset-clip> elements for each video shot
    # - Proper frame rate and timecode
    # - Audio channel mapping
    raise NotImplementedError(
        "FCPXML export — full implementation in Phase C. "
        "Requires video clips with duration metadata in log.json."
    )


def main():
    parser = argparse.ArgumentParser(
        description="Export timeline for editorial (EDL or FCPXML)",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
  python tools/export_edl.py --episode 1 --format edl
  python tools/export_edl.py --episode 1 --format fcpxml
  python tools/export_edl.py --episode 1 --format edl --output ~/Desktop/
""",
    )
    parser.add_argument(
        "--episode", "-e", type=int, required=True,
        help="Episode number to export",
    )
    parser.add_argument(
        "--format", "-f", choices=["edl", "fcpxml"], default="edl",
        help="Export format (default: edl)",
    )
    parser.add_argument(
        "--output", "-o", type=str, default=None,
        help="Output directory (default: sequences/ep_NNN/)",
    )

    args = parser.parse_args()

    # Verify log exists
    log = _load_log(args.episode)
    if log is None:
        print(
            f"No log.json found for EP{args.episode:03d}. "
            f"Run the generation pipeline first.",
            file=sys.stderr,
        )
        sys.exit(1)

    output_dir = Path(args.output) if args.output else None

    try:
        if args.format == "edl":
            path = build_edl(args.episode, output_dir)
        else:
            path = build_fcpxml(args.episode, output_dir)
        print(f"Exported: {path}")
    except NotImplementedError as e:
        print(f"Not yet implemented: {e}", file=sys.stderr)
        sys.exit(1)


if __name__ == "__main__":
    main()
