from __future__ import annotations

import base64

import pytest

from scrape_forvo.parse import extract_audio_host, iter_play_items, page_slug, safe_filename


def _b64(s: str) -> str:
    return base64.b64encode(s.encode()).decode()


def test_extract_audio_host() -> None:
    html = "var _AUDIO_HTTP_HOST = 'audio.forvo.com';"
    assert extract_audio_host(html) == "audio.forvo.com"


def test_iter_play_items_dedupe_and_order() -> None:
    mp3_a = _b64("2/s/2s_egg_1.mp3")
    mp3_b = _b64("other/egg_1.mp3")
    html = (
        "<a onclick=\"Play(123,'x','%s','%s','Label','end');return false;\">"
        % (mp3_b, mp3_a)
    )
    items = list(iter_play_items(html))
    assert len(items) == 1
    item = items[0]
    assert item.play_id == "123"
    assert item.label == "Label"
    assert item.mp3_paths[0].startswith("2/s/2s_")
    assert len(item.mp3_paths) == 2


def test_safe_filename_and_page_slug() -> None:
    assert safe_filename("  hello world ") == "hello_world"
    assert safe_filename("##") == "forvo"
    assert page_slug("https://forvo.com/search/egg/no/") == "no"
