"""CodeValidationAI — AI clinical plausibility validator."""

from __future__ import annotations

from claim_validator.models.deidentified import DeidentifiedClaim
from claim_validator.models.results import ValidatorOutput
from claim_validator.validators.ai.base import BaseAIValidator


class CodeValidationAI(BaseAIValidator):
    """Checks clinical plausibility of diagnosis-procedure pairs.

    Uses LangChain chain analysis to detect combinations that are
    clinically implausible and likely to be denied.
    """

    name = "CodeValidationAI"

    SYSTEM_PROMPT = (
        "You are a medical coding auditor. Analyze the "
        "diagnosis-procedure combinations in this claim "
        "for clinical plausibility.\n\n"
        "Respond in JSON format:\n"
        '{"findings": [\n'
        '  {"line_number": <int>, "field_name": <str>, '
        '"reason": <str>}\n'
        "]}\n\n"
        "If all combinations are clinically plausible, "
        'respond: {"findings": []}\n\n'
        "Rules:\n"
        "- Flag gender-specific procedures billed for "
        "wrong gender\n"
        "- Flag age-inappropriate procedures\n"
        "- Flag diagnosis codes that do not clinically "
        "support the procedure\n"
        "- Flag mutually exclusive diagnosis codes on the "
        "same claim (e.g., two conditions that cannot "
        "co-exist such as Type 1 and Type 2 diabetes as "
        "principal diagnoses)\n"
        "- Flag sequencing errors where a secondary code "
        "is listed as the principal diagnosis when a more "
        "specific code exists on the claim\n"
        "- Flag placeholder or unspecified diagnosis codes "
        "(e.g., codes ending in .9 or NOS codes) when a "
        "more specific code is available on the claim — "
        "report these as warnings, not errors\n"
        "- Only flag clear implausibilities, not "
        "borderline cases"
    )

    def validate_deidentified(
        self,
        claim: DeidentifiedClaim,
    ) -> ValidatorOutput:
        """Analyze clinical plausibility of claim coding."""
        return self._validate_via_chain(claim)

    def _validate_via_chain(
        self,
        claim: DeidentifiedClaim,
    ) -> ValidatorOutput:
        """Validate via LangChain chain (chain-based path)."""
        from claim_validator.chains.base import invoke_chain_safe
        from claim_validator.chains.output_schemas.code_validation import (
            CodeValidationOutput,
        )

        result = invoke_chain_safe(
            self._chain,
            {"claim_data": claim.model_dump_json()},
            fallback_output=CodeValidationOutput(
                findings=[],
                confidence=0.0,
                reasoning="Chain unavailable",
            ),
        )
        if result is None:
            return self._make_output([])
        return result.to_validator_output()
