"""PriorAuthAI — AI prior authorization 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 PriorAuthAI(BaseAIValidator):
    """Identifies services likely to require prior authorization.

    Uses LangChain chain analysis to flag procedures that commonly
    need payer pre-approval before submission.
    """

    name = "PriorAuthAI"

    SYSTEM_PROMPT = (
        "You are a healthcare prior authorization specialist. "
        "Analyze this claim to identify services that likely "
        "require prior authorization.\n\n"
        "Respond in JSON format:\n"
        '{"findings": [\n'
        '  {"field_name": <str>, "line_number": <int>, '
        '"reason": <str>}\n'
        "]}\n\n"
        "If no services require prior authorization, "
        'respond: {"findings": []}\n\n'
        "Consider:\n"
        "- High-cost imaging (MRI, CT, PET)\n"
        "- Surgical procedures above typical thresholds\n"
        "- Specialty medications and infusions\n"
        "- Durable medical equipment\n"
        "- Payer-specific prior auth requirements\n"
        "- Step therapy requirements — flag medications or "
        "treatments that typically require the patient to "
        "have tried and failed cheaper or first-line "
        "alternatives before the payer will authorize the "
        "requested therapy\n"
        "- Quantity and duration limits — flag medications "
        "or DME that exceed typical payer quantity limits "
        "or authorized duration (e.g., more than a 90-day "
        "supply, or DME rental beyond the standard "
        "authorization period)"
    )

    def validate_deidentified(
        self,
        claim: DeidentifiedClaim,
    ) -> ValidatorOutput:
        """Evaluate prior authorization requirements."""
        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.prior_auth import (
            PriorAuthOutput,
        )

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