from __future__ import annotations

from dataclasses import dataclass

from youtube_cli_agent.errors import ToolExecutionError
from youtube_cli_agent.models import VideoMetadata
from youtube_cli_agent.tools.caption_retrieval import CaptionRetrievalTool


@dataclass
class FakeCaptionBackend:
    payload_by_mode: dict[str, dict]

    def fetch(self, video_url: str, mode: str) -> dict:
        value = self.payload_by_mode.get(mode)
        if isinstance(value, Exception):
            raise value
        return value or {}


@dataclass
class FakeCaptionDownloader:
    text_by_url: dict[str, str]

    def fetch(self, url: str) -> bytes:
        return self.text_by_url[url].encode("utf-8")


def make_metadata() -> VideoMetadata:
    return VideoMetadata(
        video_id="abc123",
        title="Title",
        channel="Channel",
        url="https://www.youtube.com/watch?v=abc123",
        publish_date="2025-01-01",
        duration_seconds=300,
        description="desc",
    )


def test_caption_retrieval_prefers_manual_track() -> None:
    payload = {
        "subtitles": {
            "en": [{"ext": "vtt", "url": "https://example.test/manual.vtt"}],
        },
        "automatic_captions": {
            "en": [{"ext": "vtt", "url": "https://example.test/auto.vtt"}],
        },
    }
    backend = FakeCaptionBackend(payload_by_mode={"default": payload, "geo_bypass": payload, "alt_client": payload})
    downloader = FakeCaptionDownloader(
        text_by_url={
            "https://example.test/manual.vtt": "WEBVTT\n\n00:00:00.000 --> 00:00:04.000\nThis is a long enough manual transcript for deterministic testing and validation.",
            "https://example.test/auto.vtt": "WEBVTT\n\n00:00:00.000 --> 00:00:04.000\nThis automatic transcript should not be selected when manual exists.",
        }
    )

    tool = CaptionRetrievalTool(backend=backend, downloader=downloader, min_chars=40)
    result = tool.run(make_metadata())

    assert result.captions_available is True
    assert result.transcript is not None
    assert result.transcript.source == "Official Caption"
    assert "manual" in result.transcript.text.lower()


def test_caption_retrieval_verified_unavailable() -> None:
    backend = FakeCaptionBackend(payload_by_mode={"default": {}, "geo_bypass": {}, "alt_client": {}})
    downloader = FakeCaptionDownloader(text_by_url={})
    tool = CaptionRetrievalTool(backend=backend, downloader=downloader)

    result = tool.run(make_metadata())

    assert result.captions_available is False
    assert result.verified_unavailable is True


def test_caption_retrieval_uncertain_when_region_restricted() -> None:
    backend = FakeCaptionBackend(
        payload_by_mode={
            "default": ToolExecutionError("REGION_RESTRICTED", "Caption Retrieval", "region blocked"),
            "geo_bypass": {},
            "alt_client": {},
        }
    )
    downloader = FakeCaptionDownloader(text_by_url={})
    tool = CaptionRetrievalTool(backend=backend, downloader=downloader)

    result = tool.run(make_metadata())

    assert result.captions_available is False
    assert result.verified_unavailable is False
