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

        conditions = []
        for c in getattr(resource, "condition", None) or []:
            code = format_codeable_concept(getattr(c, "code", None))
            outcome = format_codeable_concept(getattr(c, "outcome", None))
            conditions.append({"code": code, "outcome": outcome})

        data = {
            "id": getattr(resource, "id", None),
            "relationship": format_codeable_concept(getattr(resource, "relationship", None)),
            "patient": format_reference(getattr(resource, "patient", None)),
            "condition": conditions,
        }

        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_family_history_conditions(
    family_member_history: str | dict | Any,
    *,
    raise_on_error: bool = False,
) -> dict[str, Any]:
    """Get family member history conditions."""
    try:
        if family_member_history is None or (
            isinstance(family_member_history, str) and family_member_history.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(family_member_history, "FamilyMemberHistory")
        if isinstance(resource, dict):
            if raise_on_error:
                from fhir_agent_tools._parse import FhirExtractError
                raise FhirExtractError(resource["error"])
            return resource

        conditions = []
        for c in getattr(resource, "condition", None) or []:
            code = format_codeable_concept(getattr(c, "code", None))
            outcome = format_codeable_concept(getattr(c, "outcome", None))
            conditions.append({"code": code, "outcome": outcome})

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