"""
video.py — FFmpeg-based video trimming.

Cuts a clip: (event_time - before_sec) to (event_time + after_sec).
"""

import logging
import subprocess
from pathlib import Path

logger = logging.getLogger(__name__)


def trim_clip(
    input_path: str,
    output_path: str,
    event_offset_sec: float,
    before_sec: float = 3.0,
    after_sec: float = 7.0,
) -> bool:
    """
    Trim input video around the event timestamp.

    Args:
        input_path: Full downloaded clip from SD card.
        output_path: Destination for trimmed 10-sec clip.
        event_offset_sec: Event timestamp relative to start of input clip (seconds).
        before_sec: Seconds to keep before the event.
        after_sec: Seconds to keep after the event.

    Returns:
        True on success, False on failure.
    """
    start = max(0.0, event_offset_sec - before_sec)
    duration = before_sec + after_sec

    cmd = [
        "ffmpeg",
        "-y",                          # overwrite output
        "-ss", str(start),             # seek to start position
        "-i", input_path,
        "-t", str(duration),           # duration
        "-c:v", "libx264",             # re-encode for compatibility
        "-preset", "fast",
        "-crf", "23",
        "-c:a", "aac",
        "-movflags", "+faststart",     # web-friendly
        output_path,
    ]

    logger.debug("Running FFmpeg: %s", " ".join(cmd))
    try:
        result = subprocess.run(
            cmd,
            capture_output=True,
            text=True,
            timeout=120,
        )
        if result.returncode != 0:
            logger.error("FFmpeg error:\n%s", result.stderr[-2000:])
            return False
        logger.info("Trimmed clip saved: %s", output_path)
        return True
    except subprocess.TimeoutExpired:
        logger.error("FFmpeg timed out for %s", input_path)
        return False
    except FileNotFoundError:
        logger.error("FFmpeg not found. Install with: sudo apt install ffmpeg")
        return False


def get_duration(path: str) -> float | None:
    """Return video duration in seconds using ffprobe, or None on error."""
    cmd = [
        "ffprobe",
        "-v", "error",
        "-show_entries", "format=duration",
        "-of", "default=noprint_wrappers=1:nokey=1",
        path,
    ]
    try:
        result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
        if result.returncode == 0:
            return float(result.stdout.strip())
    except Exception as exc:
        logger.warning("ffprobe failed for %s: %s", path, exc)
    return None
