"""Shared test fixtures."""

import subprocess
import tempfile
from pathlib import Path

import pytest

from takeseek.db import Database


@pytest.fixture
def tmp_db(tmp_path):
    """Create a temporary database."""
    db_path = tmp_path / "test.db"
    db = Database(db_path)
    yield db
    db.close()


@pytest.fixture
def sample_clip(tmp_db):
    """Insert a sample clip and return (db, clip_id)."""
    clip_id = tmp_db.upsert_clip(
        file_path="/videos/test_clip.mp4",
        file_name="test_clip.mp4",
        file_size=1024000,
        duration=60.0,
        width=1920,
        height=1080,
        frame_rate=29.97,
        codec="h264",
        audio_codec="aac",
        audio_sample_rate=48000,
        index_status="metadata",
    )
    return tmp_db, clip_id


@pytest.fixture(scope="session")
def test_video():
    """Generate a tiny test video using ffmpeg."""
    tmpdir = tempfile.mkdtemp()
    video_path = Path(tmpdir) / "test_video.mp4"

    try:
        subprocess.run(
            [
                "ffmpeg", "-f", "lavfi",
                "-i", "testsrc=duration=2:size=320x240:rate=30",
                "-f", "lavfi",
                "-i", "sine=frequency=440:duration=2",
                "-shortest",
                "-y", str(video_path),
            ],
            capture_output=True, text=True, timeout=30,
            check=True,
        )
    except (subprocess.CalledProcessError, FileNotFoundError) as e:
        pytest.skip(f"ffmpeg not available or failed: {e}")

    yield video_path

    # Cleanup
    import shutil
    shutil.rmtree(tmpdir, ignore_errors=True)
