from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path

from youtube_cli_agent.models import VideoMetadata
from youtube_cli_agent.tools.audio_download import AudioDownloadTool


@dataclass
class FakeAudioBackend:
    payload: bytes
    call_count: int = 0

    def download(self, video_url: str, output_template: str) -> None:
        self.call_count += 1
        out = Path(output_template.replace("%(ext)s", "m4a"))
        out.write_bytes(self.payload)


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=60,
        description="desc",
    )


def test_audio_download_and_cache_reuse(tmp_path: Path) -> None:
    backend = FakeAudioBackend(payload=b"audio-bytes")
    tool = AudioDownloadTool(backend=backend, cache_dir=tmp_path)

    first_path, first_cached = tool.run(make_metadata())
    second_path, second_cached = tool.run(make_metadata())

    assert first_path == second_path
    assert first_cached is False
    assert second_cached is True
    assert backend.call_count == 1
