"""Unit tests for the local-folder source + registry (no DB, no network)."""

from pathlib import Path

from app.core.config import Settings
from app.infrastructure.sources.local_folder import LocalFolderSource
from app.infrastructure.sources.registry import build_source_registry


def _settings(**overrides: object) -> Settings:
    return Settings(**overrides)  # type: ignore[arg-type]


def test_scan_discovers_audio_recursively(tmp_path: Path) -> None:
    (tmp_path / "a.mp3").write_bytes(b"x")
    (tmp_path / "sub").mkdir()
    (tmp_path / "sub" / "b.flac").write_bytes(b"yy")
    (tmp_path / "notes.txt").write_bytes(b"ignore me")  # non-audio → skipped

    files = list(LocalFolderSource(tmp_path).scan())
    by_id = {f.source_id: f for f in files}

    assert set(by_id) == {"a.mp3", "sub/b.flac"}
    assert by_id["a.mp3"].file_format == "mp3"
    assert by_id["a.mp3"].suggested_title == "a"
    assert by_id["sub/b.flac"].file_format == "flac"
    assert by_id["sub/b.flac"].file_size == 2


def test_source_id_is_stable_relative_path(tmp_path: Path) -> None:
    (tmp_path / "x.opus").write_bytes(b"z")
    [only] = list(LocalFolderSource(tmp_path).scan())
    assert only.source_id == "x.opus"
    assert only.path == tmp_path / "x.opus"


def test_is_available_false_when_missing(tmp_path: Path) -> None:
    source = LocalFolderSource(tmp_path / "nope")
    assert source.is_available() is False
    assert list(source.scan()) == []  # scanning an unavailable source yields nothing


def test_info_reports_kind_and_availability(tmp_path: Path) -> None:
    info = LocalFolderSource(tmp_path).info()
    assert info.name == "local"
    assert info.kind == "indexable"
    assert info.available is True


def test_registry_registers_local_when_path_set(tmp_path: Path) -> None:
    registry = build_source_registry(_settings(local_media_import_path=tmp_path))
    names = {info.name for info in registry.infos()}
    assert names == {"local"}
    assert registry.indexable("local").is_available() is True


def test_registry_empty_when_path_unset() -> None:
    registry = build_source_registry(_settings(local_media_import_path=None))
    assert registry.infos() == []
