from __future__ import annotations

import sys
from types import SimpleNamespace

from terminaluse.lib.utils import sdk_version


def test_get_codex_sdk_version_prefers_agents_module_version(monkeypatch):
    sdk_version._detect_openai_agents_version.cache_clear()
    monkeypatch.setitem(sys.modules, "agents", SimpleNamespace(__version__="0.9.3"))

    def _mock_version(_package_name: str) -> str:
        return "0.9.1"

    monkeypatch.setattr(sdk_version.importlib.metadata, "version", _mock_version)

    assert sdk_version.get_codex_sdk_version() == "0.9.3"


def test_get_codex_sdk_version_falls_back_to_metadata(monkeypatch):
    sdk_version._detect_openai_agents_version.cache_clear()
    monkeypatch.delitem(sys.modules, "agents", raising=False)

    def _mock_version(package_name: str) -> str:
        if package_name == "openai-agents":
            return "0.9.0"
        raise sdk_version.importlib.metadata.PackageNotFoundError(package_name)

    monkeypatch.setattr(sdk_version.importlib.metadata, "version", _mock_version)

    assert sdk_version.get_codex_sdk_version() == "0.9.0"


def test_get_codex_sdk_version_falls_back_when_package_missing(monkeypatch):
    sdk_version._detect_openai_agents_version.cache_clear()
    monkeypatch.delitem(sys.modules, "agents", raising=False)

    def _mock_version(_package_name: str) -> str:
        raise sdk_version.importlib.metadata.PackageNotFoundError("openai-agents")

    monkeypatch.setattr(sdk_version.importlib.metadata, "version", _mock_version)

    assert sdk_version.get_codex_sdk_version() == "0.9.0"
