"""Tests for :mod:`cyclone.parsers.cas_codes`.

Covers the public API surface:

- ``LAST_UPDATED`` module constant (parses as YYYY-MM-DD).
- :func:`reason_label` — known codes return their label, unknown codes
  fall back to ``"Unknown ({group}-{reason})"``.
- :func:`all_known_codes` — at least 100 entries, sorted, no duplicate
  ``(group, reason)`` pairs.

The dict is a snapshot of CARC (Claim Adjustment Reason Codes); tests
are deliberately decoupled from the exact labels (they change as
payers revise codes) but pin down the API contract.
"""

from __future__ import annotations

from datetime import date

import pytest

from cyclone.parsers import cas_codes


# --------------------------------------------------------------------------- #
# LAST_UPDATED
# --------------------------------------------------------------------------- #


def test_last_updated_constant() -> None:
    """``LAST_UPDATED`` is a string that parses as YYYY-MM-DD."""
    assert isinstance(cas_codes.LAST_UPDATED, str)
    parsed = date.fromisoformat(cas_codes.LAST_UPDATED)
    assert parsed.isoformat() == cas_codes.LAST_UPDATED


# --------------------------------------------------------------------------- #
# reason_label — known codes
# --------------------------------------------------------------------------- #


def test_reason_label_known_co_45() -> None:
    """CO-45 ("Charge exceeds fee schedule…") is the most-common CARC."""
    label = cas_codes.reason_label("CO", "45")
    assert isinstance(label, str)
    assert label.strip()  # non-empty
    # We don't pin the exact text (carriers revise wording); the contract
    # is "non-empty and not the unknown-fallback".
    assert "Unknown" not in label


def test_reason_label_known_pr_1() -> None:
    """PR-1 ("Deductible amount") is the bread-and-butter PR code."""
    label = cas_codes.reason_label("PR", "1")
    assert isinstance(label, str)
    assert label.strip()
    assert "Unknown" not in label


def test_reason_label_returns_specific_label_for_co_97() -> None:
    """CO-97 is the bundled-payment / included-in-payment code; pins
    that distinct codes map to distinct labels (not all the same
    fallback string)."""
    co45 = cas_codes.reason_label("CO", "45")
    co97 = cas_codes.reason_label("CO", "97")
    # Both are non-fallback but should not be identical text.
    assert co45 != co97


# --------------------------------------------------------------------------- #
# reason_label — unknown fallback
# --------------------------------------------------------------------------- #


def test_reason_label_unknown_returns_fallback() -> None:
    """Unknown (group, reason) pairs return ``"Unknown ({group}-{reason})"``."""
    assert cas_codes.reason_label("XX", "999") == "Unknown (XX-999)"
    # Even a known group with an unknown reason falls back.
    assert cas_codes.reason_label("CO", "9999") == "Unknown (CO-9999)"


# --------------------------------------------------------------------------- #
# all_known_codes — shape + invariants
# --------------------------------------------------------------------------- #


def test_all_known_codes_count_ge_100() -> None:
    """We need a useful snapshot — at least 100 codes."""
    entries = cas_codes.all_known_codes()
    assert len(entries) >= 100


def test_all_known_codes_sorted_unique() -> None:
    """Each entry is ``(group, reason, label)``; pairs are unique; result sorted."""
    entries = cas_codes.all_known_codes()
    # Shape: every entry is a 3-tuple of strings.
    for entry in entries:
        assert len(entry) == 3
        group, reason, label = entry
        assert isinstance(group, str) and group
        assert isinstance(reason, str) and reason
        assert isinstance(label, str) and label

    # Unique (group, reason) pairs.
    pairs = [(g, r) for g, r, _ in entries]
    assert len(pairs) == len(set(pairs))

    # Sorted by (group, reason) lexicographically.
    assert entries == sorted(entries)


def test_all_known_codes_includes_required_minimum_set() -> None:
    """Pin the spec's required codes so a future dict swap that drops them
    is caught here, not in production."""
    entries = cas_codes.all_known_codes()
    keys = {(g, r) for g, r, _ in entries}
    required = {
        ("CO", "45"), ("CO", "97"), ("CO", "16"), ("CO", "29"),
        ("CO", "50"), ("CO", "109"), ("CO", "119"), ("CO", "197"),
        ("CO", "204"), ("CO", "B7"), ("CO", "251"),
        ("PR", "1"), ("PR", "2"), ("PR", "3"), ("PR", "204"),
        ("OA", "23"), ("OA", "97"),
        ("PI", "16"), ("PI", "21"), ("PI", "22"), ("PI", "25"),
        ("CR", "1"), ("CR", "2"), ("CR", "3"), ("CR", "4"),
    }
    missing = required - keys
    assert not missing, f"missing required CARC codes: {sorted(missing)}"


# --------------------------------------------------------------------------- #
# reason_label — spot-check that every dict entry round-trips correctly
# --------------------------------------------------------------------------- #


@pytest.mark.parametrize("entry", list(cas_codes._CARC_LABELS.items()))
def test_reason_label_matches_dict_for_every_entry(entry) -> None:
    """Every entry in the dict returns its own label via ``reason_label``."""
    (group, reason), expected = entry
    assert cas_codes.reason_label(group, reason) == expected