"""Unit tests for registry module."""

import json
import tempfile

import pytest

from flat_fhir.registry import Registry, ColumnMapping, _registry, LOINC, SNOMED, CVX, ICD10, RXNORM


def test_constants():
    assert LOINC == "http://loinc.org"
    assert SNOMED == "http://snomed.info/sct"
    assert CVX == "http://hl7.org/fhir/sid/cvx"
    assert ICD10 == "http://hl7.org/fhir/sid/icd-10-cm"
    assert RXNORM == "http://www.nlm.nih.gov/research/umls/rxnorm"


def test_registry_lookup_known_code():
    """Heart rate (8867-4) should be in the default registry."""
    m = _registry.lookup_code(LOINC, "8867-4")
    assert m is not None
    assert m.column_name == "heart_rate_bpm"
    assert m.sheet == "vitals"


def test_registry_lookup_unknown_code():
    m = _registry.lookup_code(LOINC, "99999-9")
    assert m is None


def test_registry_lookup_column():
    m = _registry.lookup_column("heart_rate_bpm")
    assert m is not None
    assert m.code == "8867-4"


def test_registry_lookup_column_unknown():
    m = _registry.lookup_column("nonexistent_column")
    assert m is None


def test_registry_add():
    reg = Registry()
    reg.add(code="TEST-1", column_name="test_col", sheet="labs",
            system=LOINC, display="Test Measure", unit="mg/dL")
    m = reg.lookup_code(LOINC, "TEST-1")
    assert m is not None
    assert m.column_name == "test_col"
    assert m.unit == "mg/dL"


def test_registry_list():
    items = _registry.list()
    assert isinstance(items, list)
    assert len(items) > 100  # Should have 149+ mappings
    assert all("code" in item for item in items)


def test_registry_load_from_file():
    reg = Registry()
    custom = [
        {"code": "CUSTOM-1", "column_name": "custom_col", "sheet": "labs",
         "system": LOINC, "display": "Custom Test", "unit": "U/L"},
    ]
    with tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False) as f:
        json.dump(custom, f)
        f.flush()
        path = f.name

    reg.load(path)
    m = reg.lookup_code(LOINC, "CUSTOM-1")
    assert m is not None
    assert m.column_name == "custom_col"

    import os
    os.unlink(path)


def test_column_mapping_dataclass():
    m = ColumnMapping(code="1", system="sys", column_name="col", sheet="vitals")
    assert m.display == ""
    assert m.unit == ""
