"""Tests for metadata extraction."""

import pytest

from takeseek.metadata import (
    _compute_content_hash,
    _parse_frame_rate,
    is_video_file,
    extract_metadata,
    scan_directory,
)


class TestParseFrameRate:
    def test_fraction(self):
        assert _parse_frame_rate("30000/1001") == pytest.approx(29.97, abs=0.01)

    def test_integer_fraction(self):
        assert _parse_frame_rate("30/1") == 30.0

    def test_plain_number(self):
        assert _parse_frame_rate("24") == 24.0

    def test_zero_denominator(self):
        assert _parse_frame_rate("0/0") is None

    def test_empty(self):
        assert _parse_frame_rate("") is None

    def test_none(self):
        assert _parse_frame_rate(None) is None


class TestIsVideoFile:
    def test_mp4(self):
        assert is_video_file("video.mp4") is True

    def test_mov(self):
        assert is_video_file("/path/to/clip.MOV") is True

    def test_mkv(self):
        assert is_video_file("file.mkv") is True

    def test_not_video(self):
        assert is_video_file("photo.jpg") is False

    def test_txt(self):
        assert is_video_file("readme.txt") is False

    def test_no_extension(self):
        assert is_video_file("noext") is False


class TestContentHash:
    def test_content_hash_computed(self, test_video):
        meta = extract_metadata(test_video)
        assert meta.content_hash is not None
        assert len(meta.content_hash) == 64  # SHA-256 hex

    def test_content_hash_deterministic(self, test_video):
        hash1 = _compute_content_hash(test_video)
        hash2 = _compute_content_hash(test_video)
        assert hash1 == hash2


class TestExtractMetadata:
    def test_with_test_video(self, test_video):
        meta = extract_metadata(test_video)
        assert meta.file_name == "test_video.mp4"
        assert meta.width == 320
        assert meta.height == 240
        assert meta.duration > 0
        assert meta.frame_rate is not None
        assert meta.file_size > 0
        assert meta.content_hash is not None

    def test_file_not_found(self):
        with pytest.raises(Exception):
            extract_metadata("/nonexistent/video.mp4")


class TestScanDirectory:
    def test_scan_file(self, test_video):
        files = scan_directory(test_video)
        assert len(files) == 1
        assert files[0].name == "test_video.mp4"

    def test_scan_directory(self, test_video):
        files = scan_directory(test_video.parent)
        assert len(files) == 1

    def test_scan_nonexistent(self, tmp_path):
        files = scan_directory(tmp_path / "nonexistent")
        assert files == []

    def test_scan_empty_dir(self, tmp_path):
        files = scan_directory(tmp_path)
        assert files == []
