"""
Risicare SDK - Observability and self-healing for AI agents.

This package provides instrumentation for AI agent applications:
- Automatic LLM provider patching (OpenAI, Anthropic, etc.)
- Decorators for agent, session, and phase tracing
- Multiple export backends (HTTP, console, OTLP)

Quick Start:
    from risicare import init, trace, agent, session_context

    # Initialize with API key (API key determines your project)
    init(
        api_key="rsk-...",
        service_name="research-agent",  # within-project organization
        environment="production",       # within-project organization
    )

    # Tier 1: wrap LLM calls so they nest under a single trace
    @trace
    def research(query: str):
        return llm.invoke(query)          # this LLM call is a child span

    # Context manager form — groups inline LLM calls into one trace
    with trace("investment-analysis"):
        result = llm.invoke(query)        # child span, grouped into one trace

    # Tier 2: add agent identity
    @agent(name="researcher")
    @trace
    def research(query: str):
        return llm.invoke(query)

    # Tier 3: group multiple traces in a session
    with session_context(session_id="sess-123", user_id="user-456"):
        result = research("What is quantum computing?")

Progressive Integration Tiers:
    - Tier 0: RISICARE_TRACING=true (env var, 0 lines; each LLM call is its own trace)
    - Tier 1: init() + @trace or with trace() (grouped traces; minimum USEFUL setup)
    - Tier 2: @agent() decorator (agent identity + topology graph)
    - Tier 3: session_context() / @session (session grouping across traces)
    - Tier 4: @trace_think/@trace_decide/@trace_act (decision phase semantics)
    - Tier 5: @trace_message/@trace_delegate (multi-agent communication)

Note:
    Without @trace or ``with trace()``, each LLM call becomes its own independent
    trace (no parent, no grouping). Use @trace (Tier 1) to group related calls.
"""

try:
    from importlib.metadata import version as _pkg_version

    __version__ = _pkg_version("risicare")
except Exception:
    __version__ = "0.1.9"

# Re-export core types for convenience
from risicare_core import (
    AgentContext,
    AgentRole,
    MessageType,
    SemanticPhase,
    SessionContext,
    Span,
    SpanKind,
    SpanStatus,
    TraceContext,
    agent_context,
    async_agent_context,
    async_session_context,
    extract_trace_context,
    get_current_agent,
    get_current_agent_id,
    get_current_context,
    get_current_parent_span_id,
    get_current_phase,
    get_current_session,
    get_current_session_id,
    get_current_span,
    get_current_span_id,
    get_current_trace_id,
    get_span_by_id,
    get_trace_context,
    inject_trace_context,
    phase_context,
    register_span,
    restore_trace_context,
    session_context,
    traced_stream,
    traced_stream_sync,
    unregister_span,
)

# SDK-specific exports
from risicare.client import (
    RisicareClient,
    RisicareConfig,
    disable,
    enable,
    get_client,
    init,
    is_enabled,
    shutdown,
    _reset_for_testing as _reset_client_for_testing,
)
from risicare.decorators import (
    agent,
    session,
    trace,
    trace_act,
    trace_coordinate,
    trace_decide,
    trace_delegate,
    trace_message,
    trace_observe,
    trace_think,
)
from risicare.tracer import (
    Tracer,
    get_tracer,
    report_error,
    score,
    _reset_for_testing as _reset_tracer_for_testing,
)

# Fix Runtime exports
from risicare.runtime import (
    FixRuntime,
    FixLoader,
    FixApplier,
    FixCache,
    FixRuntimeConfig,
    FixInterceptor,
)
from risicare.runtime.runtime import (
    get_runtime,
    init_runtime,
    shutdown_runtime,
)

# Auto-instrumentation exports
from risicare.instrumentation import (
    install_import_hooks,
    remove_import_hooks,
    instrument_already_imported,
    is_instrumented,
    get_instrumented_modules,
    get_supported_modules,
)

# Exporter exports
from risicare.exporters.otlp import OTLPExporter


# ── Tier 0: Auto-initialize from environment variables ──────────────────────
# When RISICARE_TRACING=true and RISICARE_API_KEY is set, the SDK initializes
# automatically on import — zero lines of user code required.
import os as _os

if _os.getenv("RISICARE_TRACING", "").lower() in ("true", "1", "yes"):
    try:
        _tier0_key = _os.getenv("RISICARE_API_KEY")
        if _tier0_key:
            init(
                api_key=_tier0_key,
                endpoint=_os.getenv("RISICARE_ENDPOINT"),
                environment=_os.getenv("RISICARE_ENVIRONMENT"),
                service_name=_os.getenv("RISICARE_SERVICE_NAME"),
                debug=_os.getenv("RISICARE_DEBUG", "").lower() in ("true", "1"),
            )
    except Exception:
        import logging as _logging
        _logging.getLogger("risicare").debug("Tier 0 auto-init failed", exc_info=True)


def reset_for_testing() -> None:
    """Reset all SDK state between tests. Call in pytest fixture teardown."""
    try:
        shutdown(timeout_ms=5000)
    except Exception:
        pass
    _reset_client_for_testing()
    _reset_tracer_for_testing()
    import risicare_core
    risicare_core._reset_context_for_testing()


__all__ = [
    # Version
    "__version__",
    # Client
    "init",
    "shutdown",
    "disable",
    "enable",
    "is_enabled",
    "RisicareClient",
    "RisicareConfig",
    "get_client",
    # Tracer
    "Tracer",
    "get_tracer",
    # Error reporting & scoring
    "report_error",
    "score",
    # Decorators
    "agent",
    "session",
    "trace",
    "trace_think",
    "trace_decide",
    "trace_act",
    "trace_observe",
    "trace_message",
    "trace_delegate",
    "trace_coordinate",
    # Context managers (re-exported from core)
    "session_context",
    "async_session_context",
    "agent_context",
    "async_agent_context",
    "phase_context",
    "restore_trace_context",
    # Context accessors (re-exported from core)
    "get_current_session",
    "get_current_agent",
    "get_current_span",
    "get_current_phase",
    "get_current_context",
    "get_trace_context",
    # Convenience ID accessors (re-exported from core)
    "get_current_session_id",
    "get_current_trace_id",
    "get_current_span_id",
    "get_current_agent_id",
    "get_current_parent_span_id",
    # Span registry (re-exported from core)
    "register_span",
    "get_span_by_id",
    "unregister_span",
    # Streaming utilities (re-exported from core)
    "traced_stream",
    "traced_stream_sync",
    # W3C Trace Context (re-exported from core)
    "inject_trace_context",
    "extract_trace_context",
    # Types (re-exported from core)
    "Span",
    "SpanKind",
    "SpanStatus",
    "SessionContext",
    "AgentContext",
    "TraceContext",
    "SemanticPhase",
    "AgentRole",
    "MessageType",
    # Fix Runtime
    "FixRuntime",
    "FixLoader",
    "FixApplier",
    "FixCache",
    "FixRuntimeConfig",
    "FixInterceptor",
    "get_runtime",
    "init_runtime",
    "shutdown_runtime",
    # Auto-instrumentation
    "install_import_hooks",
    "remove_import_hooks",
    "instrument_already_imported",
    "is_instrumented",
    "get_instrumented_modules",
    "get_supported_modules",
    # Exporters
    "OTLPExporter",
    # Testing
    "reset_for_testing",
]
