"""Video frame extraction using ffmpeg."""

import logging
import subprocess
import tempfile
from dataclasses import dataclass
from pathlib import Path

logger = logging.getLogger(__name__)


class VisionError(Exception):
    """Error during frame extraction."""


@dataclass
class FrameDescription:
    timestamp: float
    description: str


def extract_frame(video_path: Path, timestamp: float, output_path: Path):
    """Extract a single frame from video at the given timestamp using ffmpeg."""
    try:
        result = subprocess.run(
            [
                "ffmpeg", "-ss", str(timestamp),
                "-i", str(video_path),
                "-frames:v", "1", "-q:v", "2",
                "-y", str(output_path),
            ],
            capture_output=True, text=True, timeout=30,
        )
    except FileNotFoundError:
        raise VisionError("ffmpeg not found. Install ffmpeg.")
    except subprocess.TimeoutExpired:
        raise VisionError(f"Frame extraction timed out at {timestamp}s")

    if result.returncode != 0:
        raise VisionError(f"Frame extraction failed: {result.stderr[:300]}")


def extract_frames(video_path: Path, duration: float, interval: float) -> list[tuple[float, Path]]:
    """Extract frames at regular intervals. Returns list of (timestamp, path).

    Caller is responsible for cleaning up the temp directory (frames[0][1].parent).
    """
    tmpdir = tempfile.mkdtemp(prefix="footage_frames_")
    frames = []

    timestamp = 0.0
    while timestamp < duration:
        output_path = Path(tmpdir) / f"frame_{timestamp:.1f}.jpg"
        try:
            extract_frame(video_path, timestamp, output_path)
            if output_path.exists() and output_path.stat().st_size > 0:
                frames.append((timestamp, output_path))
        except VisionError as e:
            logger.warning("Failed to extract frame at %.1fs: %s", timestamp, e)
        timestamp += interval

    return frames
