"""ConditionCodeValidator — validates UB-04 condition codes."""

from __future__ import annotations

import re

from claim_validator.constants import Severity
from claim_validator.models.institutional import InstitutionalClaimData
from claim_validator.models.results import Finding, ValidatorOutput
from claim_validator.validators.base import BaseValidator

_CONDITION_CODE_PATTERN = re.compile(r"^[A-Z0-9]{2}$")

# Known valid UB-04 condition codes
_KNOWN_CONDITION_CODES: set[str] = set()

# Numeric ranges
for _start, _end in [
    (1, 11), (18, 18), (20, 21), (25, 27), (31, 33),
    (38, 40), (46, 47), (50, 50), (53, 57), (60, 60),
    (66, 70), (76, 77),
]:
    for _i in range(_start, _end + 1):
        _KNOWN_CONDITION_CODES.add(f"{_i:02d}")

# Alpha ranges
for _letter in "ABCDEFGHIJKLMNOPQRSTUVWXYZ":
    for _digit in range(10):
        if _letter == "A":
            _KNOWN_CONDITION_CODES.add(f"A{_digit}")
        elif _letter == "W" and _digit <= 3:
            _KNOWN_CONDITION_CODES.add(f"W{_digit}")

# Specific alpha codes
_KNOWN_CONDITION_CODES.update({"AA", "AB"})


class ConditionCodeValidator(BaseValidator):
    """Validates condition codes on institutional (UB-04) claims."""

    name = "ConditionCodeValidator"

    def validate(self, claim: InstitutionalClaimData) -> ValidatorOutput:
        """Validate condition codes on an institutional claim."""
        findings: list[Finding] = []

        if not hasattr(claim, "condition_codes") or not claim.condition_codes:
            return self._make_output(findings)

        for code in claim.condition_codes:
            upper_code = code.upper()
            if not _CONDITION_CODE_PATTERN.match(upper_code):
                findings.append(
                    self._make_finding(
                        code="INST_INVALID_CONDITION_CODE",
                        message=f"Condition code '{code}' does not match the required 2-character alphanumeric format",
                        severity=Severity.ERROR,
                        field_name="condition_codes",
                    )
                )
            elif upper_code not in _KNOWN_CONDITION_CODES:
                findings.append(
                    self._make_finding(
                        code="INST_UNKNOWN_CONDITION_CODE",
                        message=f"Condition code {upper_code} is not in the standard UB-04 condition code set — verify it is valid",
                        severity=Severity.WARNING,
                        field_name="condition_codes",
                    )
                )

        return self._make_output(findings)
