"""Tests for the CP-10 unified element entry point."""
from pathlib import Path
import pytest

from recoil.core.ref_resolver import (
    get_element_refs, MissingCanonicalRefsError, _ALLOWED_ELEMENT_TYPES,
)


def _write_image(path: Path) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    # Minimal valid PNG
    path.write_bytes(
        b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR"
        b"\x00\x00\x00\x01\x00\x00\x00\x01\x08\x06\x00\x00\x00\x1f\x15\xc4\x89"
        b"\x00\x00\x00\rIDATx\x9cb\x00\x01\x00\x00\x05\x00\x01\r\n-\xb4"
        b"\x00\x00\x00\x00IEND\xaeB`\x82"
    )


def test_required_element_type(tmp_path, monkeypatch):
    with pytest.raises(ValueError, match="element_type must be one of"):
        get_element_refs("KIT", "driver-beware", "actor")


def test_missing_canonical_raises(tmp_path, monkeypatch):
    """No refs on disk → MissingCanonicalRefsError."""
    projects_root = tmp_path / "projects"
    projects_root.mkdir()
    (projects_root / ".recoil-data-root").write_text("recoil-data-root\n")
    # Empty project (no assets/ refs) so resolution yields {} → raise.
    proj = projects_root / "noproj"
    proj.mkdir()
    (proj / "project_config.json").write_text("{}")
    monkeypatch.setenv("RECOIL_PROJECTS_ROOT", str(projects_root))

    with pytest.raises(MissingCanonicalRefsError) as exc:
        get_element_refs("GHOST_CHAR", "noproj", "characters")
    assert "GHOST_CHAR" in str(exc.value)
    assert "char" in str(exc.value)


def test_slug_collision_no_auto_detection(tmp_path, monkeypatch):
    """If a 'KIT' character AND a 'KIT' prop both exist, type disambiguates."""
    projects_root = tmp_path / "projects"
    projects_root.mkdir()
    (projects_root / ".recoil-data-root").write_text("recoil-data-root\n")
    proj = projects_root / "p1"
    (proj / "assets").mkdir(parents=True)
    (proj / "project_config.json").write_text("{}")
    monkeypatch.setenv("RECOIL_PROJECTS_ROOT", str(projects_root))
    char_hero = proj / "assets" / "char" / "kit" / "kit_turn_hero_v01.png"
    prop_hero = proj / "assets" / "prop" / "kit" / "kit_prop_hero_v01.png"
    _write_image(char_hero)
    _write_image(prop_hero)

    char_refs = get_element_refs("KIT", "p1", "characters")
    prop_refs = get_element_refs("KIT", "p1", "props")
    assert char_refs["hero"] == char_hero
    assert prop_refs["hero"] == prop_hero
    assert char_refs["hero"] != prop_refs["hero"]


def test_allowed_types_constant():
    assert set(_ALLOWED_ELEMENT_TYPES) == {"char", "loc", "prop", "identity", "characters", "locations", "props"}
