"""Extract data from FHIR MedicationStatement 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_medication(resource: Any) -> str:
    """Extract medication from MedicationStatement."""
    med = getattr(resource, "medicationCodeableConcept", None)
    if med is not None:
        return format_codeable_concept(med)
    ref = getattr(resource, "medicationReference", None)
    if ref is not None:
        return format_reference(ref)
    return ""


def get_medication_statement_summary(
    medication_statement: str | dict | Any,
    *,
    raise_on_error: bool = False,
) -> dict[str, Any]:
    """Extract key MedicationStatement fields for LLM consumption."""
    try:
        if medication_statement is None or (
            isinstance(medication_statement, str) and medication_statement.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(medication_statement, "MedicationStatement")
        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),
            "medication": _get_medication(resource),
            "status": str(getattr(resource, "status", None)) if getattr(resource, "status", None) else None,
            "subject": format_reference(getattr(resource, "subject", None)),
            "effectiveDateTime": str(getattr(resource, "effectiveDateTime", None)) if getattr(resource, "effectiveDateTime", None) else 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_medication_statement_medication(
    medication_statement: str | dict | Any,
    *,
    raise_on_error: bool = False,
) -> dict[str, Any]:
    """Get medication from MedicationStatement."""
    try:
        if medication_statement is None or (
            isinstance(medication_statement, str) and medication_statement.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(medication_statement, "MedicationStatement")
        if isinstance(resource, dict):
            if raise_on_error:
                from fhir_agent_tools._parse import FhirExtractError
                raise FhirExtractError(resource["error"])
            return resource

        med = _get_medication(resource)
        result = {"success": True, "data": med}
        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
