# tests/test_lazy_imports.py
"""Test that lazy import fallbacks raise helpful ImportError messages."""
from __future__ import annotations

import importlib
import sys
from unittest.mock import patch

import pytest


def _reload_init_without(blocked_root: str, toolset_submod: str):
    """Reload agentsh_secure_sandbox.__init__ with *blocked_root* absent.

    Clears cached toolset submodules from sys.modules so the reload
    actually re-executes the import and hits the fallback path.
    """
    import agentsh_secure_sandbox

    # Remove cached toolset submodules so reload re-imports them
    to_remove = [
        k for k in sys.modules
        if k.startswith(f"agentsh_secure_sandbox.toolset.{toolset_submod}")
    ]
    saved = {k: sys.modules.pop(k) for k in to_remove}

    original_import = __builtins__.__import__ if hasattr(__builtins__, "__import__") else __import__

    def _guarded_import(name, *args, **kwargs):
        root = name.split(".")[0]
        if root == blocked_root:
            raise ModuleNotFoundError(name=name)
        return original_import(name, *args, **kwargs)

    try:
        with patch("builtins.__import__", side_effect=_guarded_import):
            importlib.reload(agentsh_secure_sandbox)
    except Exception:
        # Restore on failure
        sys.modules.update(saved)
        raise

    return agentsh_secure_sandbox, saved


def test_missing_pydantic_ai_gives_helpful_error():
    mod, saved = _reload_init_without("pydantic_ai", "pydantic_ai")
    try:
        with pytest.raises(ImportError, match="pydantic-ai"):
            mod.SecureSandboxToolset()
    finally:
        sys.modules.update(saved)
        importlib.reload(mod)


def test_missing_langchain_gives_helpful_error():
    mod, saved = _reload_init_without("langchain_core", "langchain")
    try:
        with pytest.raises(ImportError, match="langchain"):
            mod.SecureSandboxToolkit()
    finally:
        sys.modules.update(saved)
        importlib.reload(mod)


def test_missing_openai_agents_gives_helpful_error():
    mod, saved = _reload_init_without("agents", "openai_agents")
    try:
        with pytest.raises(ImportError, match="openai-agents"):
            mod.SecureSandboxAgentTools()
    finally:
        sys.modules.update(saved)
        importlib.reload(mod)
