"""Extract data from FHIR Condition 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_condition_summary(
    condition: str | dict | Any,
    *,
    raise_on_error: bool = False,
) -> dict[str, Any]:
    """Extract key Condition fields for LLM consumption."""
    try:
        if condition is None or (isinstance(condition, str) and condition.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(condition, "Condition")
        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)),
            "clinicalStatus": format_codeable_concept(getattr(resource, "clinicalStatus", None)),
            "verificationStatus": format_codeable_concept(getattr(resource, "verificationStatus", None)),
            "onset": _format_onset(resource),
            "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 _format_onset(resource: Any) -> str | None:
    """Format onsetDateTime, onsetPeriod, or onsetString."""
    dt = getattr(resource, "onsetDateTime", None)
    if dt is not None:
        return str(dt)
    period = getattr(resource, "onsetPeriod", None)
    if period is not None:
        return format_period(period)
    s = getattr(resource, "onsetString", None)
    if s is not None:
        return str(s)
    return None


def get_condition_code(
    condition: str | dict | Any,
    *,
    raise_on_error: bool = False,
) -> dict[str, Any]:
    """Get condition code (e.g., SNOMED)."""
    try:
        if condition is None or (isinstance(condition, str) and condition.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(condition, "Condition")
        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_condition_onset(
    condition: str | dict | Any,
    *,
    raise_on_error: bool = False,
) -> dict[str, Any]:
    """Get condition onset date/period."""
    try:
        if condition is None or (isinstance(condition, str) and condition.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(condition, "Condition")
        if isinstance(resource, dict):
            if raise_on_error:
                from fhir_agent_tools._parse import FhirExtractError
                raise FhirExtractError(resource["error"])
            return resource

        onset = _format_onset(resource)
        result = {"success": True, "data": onset}
        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_condition_clinical_status(
    condition: str | dict | Any,
    *,
    raise_on_error: bool = False,
) -> dict[str, Any]:
    """Get condition clinical status (active, resolved, etc.)."""
    try:
        if condition is None or (isinstance(condition, str) and condition.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(condition, "Condition")
        if isinstance(resource, dict):
            if raise_on_error:
                from fhir_agent_tools._parse import FhirExtractError
                raise FhirExtractError(resource["error"])
            return resource

        status = format_codeable_concept(getattr(resource, "clinicalStatus", None))
        result = {"success": True, "data": status}
        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
