"""Unit tests for domain/media.py normalization helpers."""

from media_library_viewer_api.domain.media import (
    display_media_row,
    first_media_source,
    format_date_added,
    format_rate_bits_decimal,
    is_hdr_item,
    media_streams,
    normalize_media_item,
    stream_value,
    timestamp_date_added,
)


class TestFirstMediaSource:
    def test_empty_item(self):
        assert first_media_source({}) == {}

    def test_no_sources(self):
        assert first_media_source({"MediaSources": []}) == {}

    def test_returns_first(self):
        item = {"MediaSources": [{"Id": "a"}, {"Id": "b"}]}
        assert first_media_source(item) == {"Id": "a"}


class TestMediaStreams:
    def test_empty(self):
        assert media_streams({}) == []

    def test_all_streams(self):
        item = {"MediaSources": [{"MediaStreams": [{"Type": "Video"}, {"Type": "Audio"}]}]}
        assert len(media_streams(item)) == 2

    def test_filter_by_type(self):
        item = {"MediaSources": [{"MediaStreams": [{"Type": "Video"}, {"Type": "Audio"}]}]}
        assert len(media_streams(item, "Video")) == 1
        assert len(media_streams(item, "Audio")) == 1
        assert len(media_streams(item, "Subtitle")) == 0


class TestStreamValue:
    def test_first_key(self):
        assert stream_value({"Width": 1920}, "Width", "width") == 1920

    def test_second_key(self):
        assert stream_value({"width": 1080}, "Width", "width") == 1080

    def test_none_values(self):
        assert stream_value({"Width": None, "width": 720}, "Width", "width") == 720

    def test_empty_string(self):
        assert stream_value({"Width": "", "width": 480}, "Width", "width") == 480

    def test_no_match(self):
        assert stream_value({}, "Width", "width") is None


class TestIsHdrItem:
    def test_sdr_item(self):
        item = {"MediaSources": [{"MediaStreams": [{"Type": "Video", "VideoRange": "SDR"}]}]}
        assert is_hdr_item(item) is False

    def test_hdr10(self):
        item = {"MediaSources": [{"MediaStreams": [{"Type": "Video", "VideoRange": "HDR", "VideoRangeType": "HDR10"}]}]}
        assert is_hdr_item(item) is True

    def test_dolby_vision(self):
        item = {"MediaSources": [{"MediaStreams": [{"Type": "Video", "VideoRangeType": "DolbyVision"}]}]}
        assert is_hdr_item(item) is True

    def test_bt2020_transfer(self):
        item = {"MediaSources": [{"MediaStreams": [{"Type": "Video", "ColorTransfer": "smpte2084"}]}]}
        assert is_hdr_item(item) is True

    def test_empty_item(self):
        assert is_hdr_item({}) is False


class TestFormatDateAdded:
    def test_none(self):
        assert format_date_added(None) == ""

    def test_empty(self):
        assert format_date_added("") == ""

    def test_iso_format(self):
        result = format_date_added("2024-06-15T10:30:00Z")
        assert result == "2024-06-15"


class TestTimestampDateAdded:
    def test_none(self):
        assert timestamp_date_added(None) is None

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

    def test_valid(self):
        result = timestamp_date_added("2024-01-01T00:00:00Z")
        assert isinstance(result, int)
        assert result > 0


class TestFormatRateBitsDecimal:
    def test_none(self):
        assert format_rate_bits_decimal(None) == ""

    def test_empty(self):
        assert format_rate_bits_decimal("") == ""

    def test_kbps(self):
        result = format_rate_bits_decimal(128000)
        assert "Kbps" in result

    def test_mbps(self):
        result = format_rate_bits_decimal(25_000_000)
        assert "Mbps" in result


class TestNormalizeMediaItem:
    def test_movie(self):
        item = {
            "Id": "abc123",
            "Name": "Test Movie",
            "Type": "Movie",
            "ProductionYear": 2024,
            "RunTimeTicks": 72000000000,  # 120 minutes
            "Path": "/media/movies/Test Movie (2024)/file.mkv",
            "DateCreated": "2024-06-15T10:00:00Z",
            "MediaSources": [{
                "Size": 5368709120,
                "Bitrate": 25000000,
                "MediaStreams": [
                    {"Type": "Video", "Codec": "hevc", "Width": 3840, "Height": 2160, "VideoRange": "HDR"},
                    {"Type": "Audio", "Codec": "truehd"},
                ],
            }],
        }
        row = normalize_media_item(item, "lib1", "Movies")
        assert row["id"] == "abc123"
        assert row["title"] == "Test Movie"
        assert row["type"] == "Movie"
        assert row["year"] == 2024
        assert row["runtime_min"] == 120
        assert row["size_bytes"] == 5368709120
        assert "GB" in row["size"]
        assert row["bitrate_bps"] == 25000000
        assert "Mbps" in row["bitrate"]
        assert row["hdr"] == 1
        assert row["video"] == "hevc"
        assert row["width"] == 3840
        assert row["height"] == 2160
        assert row["resolution"] == "3840x2160"
        assert row["library_id"] == "lib1"
        assert row["library_name"] == "Movies"

    def test_episode(self):
        item = {
            "Id": "ep1",
            "Name": "Pilot",
            "SeriesName": "Breaking Bad",
            "ParentIndexNumber": 1,
            "IndexNumber": 1,
            "Type": "Episode",
            "MediaSources": [{"MediaStreams": [{"Type": "Video", "Codec": "h264", "Width": 1920, "Height": 1080}]}],
        }
        row = normalize_media_item(item)
        assert row["series"] == "Breaking Bad"
        assert row["season"] == "S01"
        assert row["season_number"] == 1
        assert row["episode"] == 1
        assert row["hdr"] == 0

    def test_minimal_item(self):
        item = {"Id": "x", "Name": "Minimal"}
        row = normalize_media_item(item)
        assert row["id"] == "x"
        assert row["title"] == "Minimal"
        assert row["size_bytes"] is None
        assert row["bitrate_bps"] is None


class TestDisplayMediaRow:
    def test_basic(self):
        row = {
            "title": "Test",
            "series": "",
            "season": "",
            "episode": None,
            "type": "Movie",
            "year": 2024,
            "runtime_min": 120,
            "size": "5.0 GB",
            "size_bytes": 5000000000,
            "bitrate": "25.0 Mbps",
            "bitrate_bps": 25000000,
            "hdr": 1,
            "video": "hevc",
            "resolution": "3840x2160",
            "date_added": "2024-06-15",
            "library_name": "Movies",
            "path": "/path/to/file.mkv",
            "id": "abc",
        }
        display = display_media_row(row)
        assert display["title"] == "Test"
        assert display["hdr"] == "yes"
        assert display["library"] == "Movies"

    def test_sdr(self):
        row = {"hdr": 0, "title": "X", "id": "y"}
        display = display_media_row(row)
        assert display["hdr"] == "no"
