import asyncio
import traceback
from typing import List, Optional
from langchain_core.tools import StructuredTool

from mcp_integration.client import MCPClient
from mcp_integration.tool_wrapper import create_tool_wrapper


_tools_cache: Optional[List[StructuredTool]] = None
_client = MCPClient()


async def get_tools_async() -> List[StructuredTool]:
    """Returns MCP tools (async). Caches results after the first call."""
    global _tools_cache
    if _tools_cache is not None:
        return _tools_cache

    try:
        print("⏳ Fetching tools from MCP server (async)...")
        raw_tools = await _client.get_raw_tools()
        if raw_tools:
            print(f"✅ Tools found: {[t.name for t in raw_tools]}")
            _tools_cache = [create_tool_wrapper(t) for t in raw_tools]
            return _tools_cache
        return []
    except Exception:
        print("❌ Error fetching MCP tools:")
        traceback.print_exc()
        return []


def get_tools() -> List[StructuredTool]:
    """Returns MCP tools (sync). Must NOT be called inside a running event loop."""
    global _tools_cache
    if _tools_cache is not None:
        return _tools_cache

    try:
        asyncio.get_running_loop()
        print("⚠️ Event loop detected — use get_tools_async() instead.")
        return []
    except RuntimeError:
        pass

    try:
        print("⏳ Fetching tools from MCP server (sync)...")
        raw_tools = asyncio.run(_client.get_raw_tools())
        if raw_tools:
            print(f"✅ Tools found: {[t.name for t in raw_tools]}")
            _tools_cache = [create_tool_wrapper(t) for t in raw_tools]
            return _tools_cache
        return []
    except Exception:
        print("❌ Error fetching MCP tools:")
        traceback.print_exc()
        return []
