"""Extract data from FHIR CareTeam 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_care_team_summary(
    care_team: str | dict | Any,
    *,
    raise_on_error: bool = False,
) -> dict[str, Any]:
    """Extract key CareTeam fields for LLM consumption."""
    try:
        if care_team is None or (isinstance(care_team, str) and care_team.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(care_team, "CareTeam")
        if isinstance(resource, dict):
            if raise_on_error:
                from fhir_agent_tools._parse import FhirExtractError
                raise FhirExtractError(resource["error"])
            return resource

        members = []
        for m in getattr(resource, "member", None) or []:
            role = format_codeable_concept(getattr(m, "role", None))
            member_ref = format_reference(getattr(m, "member", None))
            members.append({"role": role, "member": member_ref})

        data = {
            "id": getattr(resource, "id", None),
            "status": str(getattr(resource, "status", None)) if getattr(resource, "status", None) else None,
            "subject": format_reference(getattr(resource, "subject", None)),
            "member": members,
        }

        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_care_team_members(
    care_team: str | dict | Any,
    *,
    raise_on_error: bool = False,
) -> dict[str, Any]:
    """Get care team members with roles."""
    try:
        if care_team is None or (isinstance(care_team, str) and care_team.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(care_team, "CareTeam")
        if isinstance(resource, dict):
            if raise_on_error:
                from fhir_agent_tools._parse import FhirExtractError
                raise FhirExtractError(resource["error"])
            return resource

        members = []
        for m in getattr(resource, "member", None) or []:
            role = format_codeable_concept(getattr(m, "role", None))
            member_ref = format_reference(getattr(m, "member", None))
            members.append({"role": role, "member": member_ref})

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