from services.archive import (
    Archive,
    ArchiveWelcome,
    DEFAULT_ARCHIVE_WELCOME,
    Material,
    build_archive_keyboard,
    format_list_materials,
    format_material_response,
    resolve_welcome_text,
)


def _mat(id_: str, title: str = "T", url: str = "https://x") -> Material:
    return Material(id=id_, title=title, description="d", url=url)


def test_build_archive_keyboard_one_button_per_material():
    archive = Archive(welcome=None, materials=[_mat("a", "Aaa"), _mat("b", "Bbb")])
    keyboard = build_archive_keyboard(archive.materials)
    rows = keyboard.inline_keyboard
    assert len(rows) == 2
    assert rows[0][0].text == "Aaa"
    assert rows[0][0].callback_data == "material:a"
    assert rows[1][0].text == "Bbb"
    assert rows[1][0].callback_data == "material:b"


def test_build_archive_keyboard_empty_returns_none():
    assert build_archive_keyboard([]) is None


def test_format_material_response_returns_text_and_url_keyboard():
    mat = _mat("bat", title="Бат · июнь", url="https://youtu.be/x")
    mat.description = "<b>Запись</b> вебинара"
    text, keyboard = format_material_response(mat, gated=False)
    assert text == "<b>Бат · июнь</b>\n\n<b>Запись</b> вебинара"
    assert keyboard.inline_keyboard[0][0].text == "🔗 Смотреть запись"
    assert keyboard.inline_keyboard[0][0].url == "https://youtu.be/x"


def test_format_list_materials_with_items():
    materials = [_mat("a", "Aaa", "https://x"), _mat("b", "Bbb", "https://y")]
    text = format_list_materials(materials)
    assert "1. Aaa" in text
    assert "id: a" in text
    assert "label: 🔗 Смотреть запись" in text
    assert "url: https://x" in text
    assert "2. Bbb" in text
    assert "id: b" in text


def test_format_list_materials_empty():
    assert format_list_materials([]) == "Материалов нет."


def test_resolve_welcome_text_uses_archive_welcome():
    archive = Archive(welcome=ArchiveWelcome(text="Custom hi"), materials=[])
    assert resolve_welcome_text(archive) == "Custom hi"


def test_resolve_welcome_text_falls_back_when_none():
    archive = Archive(welcome=None, materials=[])
    assert resolve_welcome_text(archive) == DEFAULT_ARCHIVE_WELCOME


def test_resolve_welcome_text_falls_back_when_empty_text():
    archive = Archive(welcome=ArchiveWelcome(text=""), materials=[])
    assert resolve_welcome_text(archive) == DEFAULT_ARCHIVE_WELCOME
