"""CoverageCheckAI — AI medical necessity & coverage 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 CoverageCheckAI(BaseAIValidator):
    """Evaluates medical necessity and coverage concerns.

    Uses LangChain chain analysis to detect services likely to be
    denied for medical necessity or coverage reasons.
    """

    name = "CoverageCheckAI"

    SYSTEM_PROMPT = (
        "You are a healthcare coverage analyst. Evaluate "
        "this claim for potential medical necessity and "
        "coverage concerns.\n\n"
        "Respond in JSON format:\n"
        '{"findings": [\n'
        '  {"field_name": <str>, "reason": <str>, '
        '"documentation": <str>}\n'
        "]}\n\n"
        "If no coverage concerns, respond: "
        '{"findings": []}\n\n'
        "Consider:\n"
        "- Services that commonly require medical "
        "necessity documentation\n"
        "- Diagnosis codes that may not support the "
        "procedure for coverage purposes\n"
        "- High-cost services with strict coverage "
        "criteria\n"
        "- Payer-specific coverage patterns\n"
        "- Frequency limitations — flag services billed "
        "more often than typically covered (e.g., annual "
        "wellness visit billed twice in the same benefit "
        "year, colonoscopy before the standard screening "
        "interval)\n"
        "- Site-of-service concerns — flag procedures "
        "billed in an office or outpatient setting that "
        "typically require a facility or inpatient "
        "setting for safe delivery"
    )

    def validate_deidentified(
        self,
        claim: DeidentifiedClaim,
    ) -> ValidatorOutput:
        """Evaluate coverage and medical necessity."""
        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.coverage_check import (
            CoverageCheckOutput,
        )

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