"""M11 抽帧测试：用 ffmpeg 生成测试视频，验证 extract_frames 产出帧卡片。

无 ffmpeg 时自动跳过（CI/本地可能没装）。
"""
from __future__ import annotations

import shutil
import subprocess
from pathlib import Path

import pytest


def _ffmpeg() -> str | None:
    try:
        import imageio_ffmpeg
        return imageio_ffmpeg.get_ffmpeg_exe()
    except Exception:
        return shutil.which("ffmpeg")


FF = _ffmpeg()


@pytest.mark.skipif(not FF, reason="ffmpeg 不可用")
def test_extract_frames_from_generated_clip(tmp_path):
    from decode_content.readers.video_frames import extract_frames
    from core.models import Card

    clip = tmp_path / "clip.mp4"
    subprocess.run(
        [FF, "-y", "-f", "lavfi", "-i",
         "testsrc=duration=6:size=320x240:rate=10", str(clip)],
        capture_output=True,
    )
    assert clip.exists()

    cards = extract_frames(str(clip), out_dir=str(tmp_path / "f"),
                           url_prefix="/frames/x", max_frames=8)
    assert len(cards) >= 1
    assert all(isinstance(c, Card) and c.kind == "frame" for c in cards)
    assert all(c.url.startswith("/frames/x/") for c in cards)
    # 帧文件确实生成
    assert all((tmp_path / "f" / Path(c.url).name).exists() for c in cards)
    # 1-based 连续索引
    assert [c.index for c in cards] == list(range(1, len(cards) + 1))
