"""Extract data from FHIR Goal 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 _format_target(t) -> dict[str, Any] | None:
    """Format goal target."""
    if t is None:
        return None
    measure = format_codeable_concept(getattr(t, "measure", None))
    detail = getattr(t, "detailQuantity", None) or getattr(t, "detailInteger", None) or getattr(t, "detailRange", None)
    detail_val = str(detail) if detail is not None else None
    due = getattr(t, "dueDate", None) or getattr(t, "dueDuration", None)
    due_val = str(due) if due is not None else None
    return {"measure": measure, "detail": detail_val, "due": due_val}


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

        targets = []
        for t in getattr(resource, "target", None) or []:
            fmt = _format_target(t)
            if fmt:
                targets.append(fmt)

        data = {
            "id": getattr(resource, "id", None),
            "description": format_codeable_concept(getattr(resource, "description", None)),
            "status": str(getattr(resource, "lifecycleStatus", None)) if getattr(resource, "lifecycleStatus", None) else None,
            "subject": format_reference(getattr(resource, "subject", None)),
            "target": targets,
        }

        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_goal_description(
    goal: str | dict | Any,
    *,
    raise_on_error: bool = False,
) -> dict[str, Any]:
    """Get goal description."""
    try:
        if goal is None or (isinstance(goal, str) and goal.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(goal, "Goal")
        if isinstance(resource, dict):
            if raise_on_error:
                from fhir_agent_tools._parse import FhirExtractError
                raise FhirExtractError(resource["error"])
            return resource

        desc = format_codeable_concept(getattr(resource, "description", None))
        result = {"success": True, "data": desc}
        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_goal_target(
    goal: str | dict | Any,
    *,
    raise_on_error: bool = False,
) -> dict[str, Any]:
    """Get goal target(s)."""
    try:
        if goal is None or (isinstance(goal, str) and goal.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(goal, "Goal")
        if isinstance(resource, dict):
            if raise_on_error:
                from fhir_agent_tools._parse import FhirExtractError
                raise FhirExtractError(resource["error"])
            return resource

        targets = []
        for t in getattr(resource, "target", None) or []:
            fmt = _format_target(t)
            if fmt:
                targets.append(fmt)

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