"""
LangChain Adapter

Adapts Jarvis tools to LangChain tool format.
"""

from typing import List, Dict, Any, Optional, Callable
import json


class LangChainToolAdapter:
    """Adapter for converting Jarvis tools to LangChain tools"""

    def __init__(self, registry: Any):
        self.registry = registry

    def to_langchain_tools(self) -> List[Dict[str, Any]]:
        """Convert all enabled tools to LangChain format"""
        import asyncio

        async def _convert():
            tools = await self.registry.list_enabled()
            result = []

            for metadata in tools:
                lc_tool = await self._create_langchain_tool(metadata)
                if lc_tool:
                    result.append(lc_tool)

            return result

        return asyncio.get_event_loop().run_until_complete(_convert())

    async def _create_langchain_tool(self, metadata: Any) -> Optional[Dict[str, Any]]:
        """Create a single LangChain tool from metadata"""
        executor = await self.registry.get_executor(metadata.name)
        if not executor:
            return None

        config = await self.registry.get_config(metadata.name)

        return {
            "name": metadata.name,
            "description": metadata.description,
            "display_name": metadata.display_name,
            "tags": metadata.tags,
            "version": metadata.version,
            "executor": executor,
            "config": config,
        }

    def get_tool_schemas(self) -> List[Dict[str, Any]]:
        """Get tool schemas for LLM function calling"""
        import asyncio

        async def _get():
            tools = await self.registry.list_enabled()
            schemas = []

            for tool in tools:
                schemas.append(
                    {
                        "name": tool.name,
                        "description": tool.description,
                        "parameters": {
                            "type": "object",
                            "properties": {},
                            "required": [],
                        },
                    }
                )

            return schemas

        return asyncio.get_event_loop().run_until_complete(_get())
