from __future__ import annotations

import io
import os
from pathlib import Path

from scrape_forvo.download import download_audio, select_audio_url
from scrape_forvo.types import PlayItem


class _DummyResponse:
    def __init__(self, status_code: int, body: bytes = b"") -> None:
        self.status_code = status_code
        self._body = body

    def raise_for_status(self) -> None:
        if self.status_code >= 400:
            raise RuntimeError("bad status")

    def iter_content(self, chunk_size: int = 1024) -> list[bytes]:
        return [self._body]

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc, tb):
        return False


class _DummySession:
    def __init__(self, head_status: int = 200, body: bytes = b"") -> None:
        self._head_status = head_status
        self._body = body

    def head(self, url: str, allow_redirects: bool = True, timeout: int = 15):
        return _DummyResponse(self._head_status)

    def get(self, url: str, stream: bool = True, timeout: int = 30):
        return _DummyResponse(200, self._body)


def test_select_audio_url_respects_no_head() -> None:
    item = PlayItem(play_id="1", label="x", mp3_paths=("a.mp3", "b.mp3"))
    session = _DummySession(head_status=404)
    url = select_audio_url(item, "https://host/audios/mp3", session, no_head=True, seen_urls=set())
    assert url == "https://host/audios/mp3/a.mp3"


def test_select_audio_url_uses_head() -> None:
    item = PlayItem(play_id="1", label="x", mp3_paths=("a.mp3",))
    session = _DummySession(head_status=404)
    url = select_audio_url(item, "https://host/audios/mp3", session, no_head=False, seen_urls=set())
    assert url is None


def test_download_audio_writes_file(tmp_path: Path) -> None:
    session = _DummySession(body=b"abc123")
    out_path = tmp_path / "out.mp3"
    download_audio("https://host/audios/mp3/a.mp3", str(out_path), session)
    assert out_path.read_bytes() == b"abc123"
