"""Extract data from FHIR Procedure 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_period, format_reference


def get_procedure_summary(
    procedure: str | dict | Any,
    *,
    raise_on_error: bool = False,
) -> dict[str, Any]:
    """Extract key Procedure fields for LLM consumption."""
    try:
        if procedure is None or (isinstance(procedure, str) and procedure.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(procedure, "Procedure")
        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),
            "code": format_codeable_concept(getattr(resource, "code", None)),
            "status": str(getattr(resource, "status", None)) if getattr(resource, "status", None) else None,
            "performedDateTime": str(getattr(resource, "performedDateTime", None)) if getattr(resource, "performedDateTime", None) else None,
            "performedPeriod": format_period(getattr(resource, "performedPeriod", None)),
            "subject": format_reference(getattr(resource, "subject", 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_procedure_code(
    procedure: str | dict | Any,
    *,
    raise_on_error: bool = False,
) -> dict[str, Any]:
    """Get procedure code."""
    try:
        if procedure is None or (isinstance(procedure, str) and procedure.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(procedure, "Procedure")
        if isinstance(resource, dict):
            if raise_on_error:
                from fhir_agent_tools._parse import FhirExtractError
                raise FhirExtractError(resource["error"])
            return resource

        code = format_codeable_concept(getattr(resource, "code", None))
        result = {"success": True, "data": code}
        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_procedure_performed(
    procedure: str | dict | Any,
    *,
    raise_on_error: bool = False,
) -> dict[str, Any]:
    """Get procedure performed date/period."""
    try:
        if procedure is None or (isinstance(procedure, str) and procedure.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(procedure, "Procedure")
        if isinstance(resource, dict):
            if raise_on_error:
                from fhir_agent_tools._parse import FhirExtractError
                raise FhirExtractError(resource["error"])
            return resource

        dt = getattr(resource, "performedDateTime", None)
        if dt is not None:
            performed = str(dt)
        else:
            performed = format_period(getattr(resource, "performedPeriod", None))

        result = {"success": True, "data": performed}
        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
