"""Tests for compiler/stages/transcribe.py — offline via fake downloader/model."""

from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path

from compiler.stages.transcribe import (
    _resolve_audio_url,
    is_audio_source,
    transcribe_all,
    transcribe_source,
)


@dataclass
class _Segment:
    start: float
    end: float
    text: str
    speaker: str = "SPEAKER_01"


class _FakeModel:
    def __init__(self) -> None:
        self.calls = 0

    def transcribe(self, audio: str, **kwargs):
        self.calls += 1
        assert audio.endswith(".m4a")
        assert kwargs["language"] == "en"
        return (
            [
                _Segment(0.0, 1.25, "Hello from the archive."),
                _Segment(1.5, 3.0, "This is the second turn."),
            ],
            {"language": "en"},
        )


def _fake_downloader(src: dict, media_dir: Path) -> Path:
    media_dir.mkdir(parents=True, exist_ok=True)
    path = media_dir / f"{src['id']}.m4a"
    path.write_bytes(b"fake audio")
    return path


def test_is_audio_source_matches_audio_fetch_types_and_source_types():
    assert is_audio_source({"id": "x", "fetch_type": "youtube"})
    assert is_audio_source({"id": "x", "fetch_type": "rss"})
    assert is_audio_source({"id": "x", "type": "interview"})
    assert not is_audio_source({"id": "x", "fetch_type": "url", "type": "article"})


def test_transcribe_source_downloads_and_writes_timestamped_transcript(tmp_path):
    model = _FakeModel()
    src = {
        "id": "interview-1",
        "type": "interview",
        "fetch_type": "youtube",
        "url": "https://example.com/watch?v=1",
        "language": "en",
    }

    result = transcribe_source(
        src,
        tmp_path / "raw",
        downloader=_fake_downloader,
        model=model,
    )

    assert result == tmp_path / "raw" / "interview-1.txt"
    transcript = result.read_text()
    assert "[00:00:00.000 --> 00:00:01.250] SPEAKER_01: Hello from the archive." in transcript
    assert "[00:00:01.500 --> 00:00:03.000] SPEAKER_01: This is the second turn." in transcript
    assert model.calls == 1


def test_transcribe_source_uses_cached_transcript(tmp_path):
    model = _FakeModel()
    raw_dir = tmp_path / "raw"
    raw_dir.mkdir()
    cached = raw_dir / "interview-1.txt"
    cached.write_text("cached transcript\n")
    src = {"id": "interview-1", "type": "interview", "fetch_type": "youtube"}

    result = transcribe_source(src, raw_dir, downloader=_fake_downloader, model=model)

    assert result == cached
    assert cached.read_text() == "cached transcript\n"
    assert model.calls == 0


def test_transcribe_all_skips_text_sources(tmp_path):
    model = _FakeModel()
    sources = [
        {"id": "article-1", "type": "article", "fetch_type": "url"},
        {"id": "podcast-1", "type": "podcast", "fetch_type": "rss", "rss_url": "https://x.test/rss"},
    ]

    results = transcribe_all(
        sources,
        tmp_path / "raw",
        downloader=_fake_downloader,
        model=model,
    )

    assert list(results) == ["podcast-1"]
    assert results["podcast-1"].exists()
    assert model.calls == 1


def test_resolve_audio_url_prefers_episode_url():
    assert (
        _resolve_audio_url(
            {
                "id": "podcast-1",
                "fetch_type": "rss",
                "rss_url": "https://example.com/feed.xml",
                "episode_url": "https://cdn.example.com/episode.mp3",
            }
        )
        == "https://cdn.example.com/episode.mp3"
    )


def test_resolve_audio_url_from_rss_enclosure(tmp_path):
    feed = tmp_path / "feed.xml"
    feed.write_text(
        """<?xml version="1.0"?>
<rss version="2.0">
  <channel>
    <item>
      <title>Episode 1</title>
      <enclosure url="https://cdn.example.com/episode-1.mp3" type="audio/mpeg"/>
    </item>
  </channel>
</rss>
"""
    )

    assert (
        _resolve_audio_url(
            {
                "id": "podcast-1",
                "fetch_type": "rss",
                "rss_url": str(feed),
            }
        )
        == "https://cdn.example.com/episode-1.mp3"
    )
