from pathlib import Path

from hef.catalog import Record, save_catalog, load_catalog
from hef.selection import Coordinate, select

REPO_ROOT = Path(__file__).resolve().parent.parent


def _rec(id, mode, left, right, dark, light):
    return Record(
        id=id,
        title=id,
        source_url=f"https://example.org/{id}",
        source_archive="internet_archive",
        license="public_domain",
        mode=mode,
        left=left,
        right=right,
        dark=dark,
        light=light,
        duration_s=600,
        file_path=f"/media/{id}.mp4",
    )


def test_catalog_round_trip_then_select(tmp_path):
    library = [
        _rec("lecture", "av", left=4, right=0, dark=1, light=2),
        _rec("nebula", "video", left=0, right=4, dark=2, light=3),
        _rec("storm", "av", left=0, right=3, dark=4, light=0),
        _rec("sunrise", "av", left=1, right=3, dark=0, light=4),
    ]
    path = tmp_path / "library.jsonl"
    save_catalog(library, path)
    loaded = load_catalog(path)

    # A right-brain, very-light tuning should land on "sunrise".
    chosen = select(loaded, Coordinate(left=1, right=3, dark=0, light=4), "av")
    assert chosen.id == "sunrise"

    # The void state returns nothing regardless of library.
    assert select(loaded, Coordinate(0, 0, 0, 0), "none") is None


def test_committed_empty_catalog_loads():
    path = REPO_ROOT / "catalog" / "library.jsonl"
    assert load_catalog(path) == []
