"""Extract data from FHIR Immunization resources."""

from __future__ import annotations

from typing import Any

from fhir_agent_tools._parse import _error, _parse_resource
from fhir_agent_tools._utils import format_codeable_concept, format_reference


def get_immunization_summary(
    immunization: str | dict | Any,
    *,
    raise_on_error: bool = False,
) -> dict[str, Any]:
    """Extract key Immunization fields for LLM consumption."""
    try:
        if immunization is None or (isinstance(immunization, str) and immunization.strip() == ""):
            err = _error("empty_input", "No input provided")
            if raise_on_error:
                from fhir_agent_tools._parse import FhirExtractError
                raise FhirExtractError(err["error"])
            return err

        resource = _parse_resource(immunization, "Immunization")
        if isinstance(resource, dict):
            if raise_on_error:
                from fhir_agent_tools._parse import FhirExtractError
                raise FhirExtractError(resource["error"])
            return resource

        data = {
            "id": getattr(resource, "id", None),
            "vaccineCode": format_codeable_concept(getattr(resource, "vaccineCode", None)),
            "status": str(getattr(resource, "status", None)) if getattr(resource, "status", None) else None,
            "occurrenceDateTime": str(getattr(resource, "occurrenceDateTime", None)) if getattr(resource, "occurrenceDateTime", None) else None,
            "patient": format_reference(getattr(resource, "patient", None)),
        }

        result = {"success": True, "data": data}
        if raise_on_error:
            return result["data"]
        return result

    except Exception as e:
        err = _error("unexpected_error", str(e), details=repr(e))
        if raise_on_error:
            from fhir_agent_tools._parse import FhirExtractError
            raise FhirExtractError(err["error"])
        return err


def get_immunization_vaccine(
    immunization: str | dict | Any,
    *,
    raise_on_error: bool = False,
) -> dict[str, Any]:
    """Get immunization vaccine code."""
    try:
        if immunization is None or (isinstance(immunization, str) and immunization.strip() == ""):
            err = _error("empty_input", "No input provided")
            if raise_on_error:
                from fhir_agent_tools._parse import FhirExtractError
                raise FhirExtractError(err["error"])
            return err

        resource = _parse_resource(immunization, "Immunization")
        if isinstance(resource, dict):
            if raise_on_error:
                from fhir_agent_tools._parse import FhirExtractError
                raise FhirExtractError(resource["error"])
            return resource

        vaccine = format_codeable_concept(getattr(resource, "vaccineCode", None))
        result = {"success": True, "data": vaccine}
        if raise_on_error:
            return result["data"]
        return result

    except Exception as e:
        err = _error("unexpected_error", str(e), details=repr(e))
        if raise_on_error:
            from fhir_agent_tools._parse import FhirExtractError
            raise FhirExtractError(err["error"])
        return err


def get_immunization_date(
    immunization: str | dict | Any,
    *,
    raise_on_error: bool = False,
) -> dict[str, Any]:
    """Get immunization date (occurrenceDateTime)."""
    try:
        if immunization is None or (isinstance(immunization, str) and immunization.strip() == ""):
            err = _error("empty_input", "No input provided")
            if raise_on_error:
                from fhir_agent_tools._parse import FhirExtractError
                raise FhirExtractError(err["error"])
            return err

        resource = _parse_resource(immunization, "Immunization")
        if isinstance(resource, dict):
            if raise_on_error:
                from fhir_agent_tools._parse import FhirExtractError
                raise FhirExtractError(resource["error"])
            return resource

        dt = getattr(resource, "occurrenceDateTime", None)
        date_val = str(dt) if dt is not None else None
        result = {"success": True, "data": date_val}
        if raise_on_error:
            return result["data"]
        return result

    except Exception as e:
        err = _error("unexpected_error", str(e), details=repr(e))
        if raise_on_error:
            from fhir_agent_tools._parse import FhirExtractError
            raise FhirExtractError(err["error"])
        return err
