"""SDK version detection utilities."""

from __future__ import annotations

import importlib.metadata
from functools import lru_cache

MIN_CODEXADAPTER_OPENAI_AGENTS_VERSION = "0.9.0"


def get_claude_sdk_version() -> str:
    """Get the Claude SDK version, with fallback."""
    try:
        import claude_agent_sdk

        return claude_agent_sdk.__version__
    except (ImportError, AttributeError):
        return "0.0.0-unknown"


def get_codex_sdk_version() -> str:
    """Get canonical Codex adapter version from installed openai-agents package."""
    detected_version = _detect_openai_agents_version()
    if detected_version:
        return detected_version

    # Fallback to the minimum 0.x version supported by the backend CodexAdapter.
    return MIN_CODEXADAPTER_OPENAI_AGENTS_VERSION


@lru_cache(maxsize=1)
def _detect_openai_agents_version() -> str | None:
    """Detect openai-agents package version for codex_tool-backed runtimes."""
    try:
        import agents

        module_version = getattr(agents, "__version__", None)
        if isinstance(module_version, str) and module_version:
            return module_version
    except ImportError:
        pass

    for package_name in ("openai-agents", "openai_agents"):
        try:
            return importlib.metadata.version(package_name)
        except importlib.metadata.PackageNotFoundError:
            continue
    return None


# SDK type constants
SDK_TYPE_CLAUDE = "claude"
SDK_TYPE_CODEX = "codex"
SDK_TYPE_TERMINAL_USE = "terminal_use"
DEFAULT_TERMINAL_USE_VERSION = "1.0.0"
