"""
LangChain integration for Authevo.

This module provides a VerifiableTool that wraps Authevo actions as LangChain tools.
"""

from typing import Optional, Type, Any
from pydantic import BaseModel, Field

try:
    from langchain.tools import BaseTool
    from langchain.callbacks.manager import CallbackManagerForToolRun
except ImportError:
    raise ImportError(
        "LangChain is required for this module. Install it with: pip install langchain"
    )

from .agent import AuthevoAgent


class VerifiableToolInput(BaseModel):
    """Input schema for VerifiableTool."""
    payload: dict = Field(description="Action payload as a dictionary")


class VerifiableTool(BaseTool):
    """
    LangChain tool that executes verifiable Authevo actions.
    
    Example:
        >>> agent = AuthevoAgent.generate()
        >>> refund_tool = VerifiableTool(
        ...     name="refund",
        ...     description="Issue refund with policy enforcement",
        ...     authevo_agent=agent,
        ...     action="refund"
        ... )
        >>> # Use with LangChain
        >>> result = refund_tool.run({"payload": {"orderId": "123", "amount": 50}})
    """
    
    name: str = "authevo_action"
    description: str = "Execute a verifiable action with Authevo"
    args_schema: Type[BaseModel] = VerifiableToolInput
    
    authevo_agent: AuthevoAgent
    action: str
    
    class Config:
        arbitrary_types_allowed = True
    
    def _run(
        self,
        payload: dict,
        run_manager: Optional[CallbackManagerForToolRun] = None
    ) -> str:
        """
        Execute the Authevo action.
        
        Args:
            payload: Action payload dictionary
            run_manager: LangChain callback manager (optional)
            
        Returns:
            JSON string with action result
        """
        try:
            # Execute action through Authevo
            import asyncio
            result = asyncio.run(
                self.authevo_agent.execute_action(
                    action=self.action,
                    payload=payload
                )
            )
            
            # Return formatted result
            return f"Action executed successfully. Action ID: {result.get('actionId', 'unknown')}"
            
        except Exception as e:
            return f"Action failed: {str(e)}"
    
    async def _arun(
        self,
        payload: dict,
        run_manager: Optional[CallbackManagerForToolRun] = None
    ) -> str:
        """
        Async version of _run.
        
        Args:
            payload: Action payload dictionary
            run_manager: LangChain callback manager (optional)
            
        Returns:
            JSON string with action result
        """
        try:
            result = await self.authevo_agent.execute_action(
                action=self.action,
                payload=payload
            )
            
            return f"Action executed successfully. Action ID: {result.get('actionId', 'unknown')}"
            
        except Exception as e:
            return f"Action failed: {str(e)}"
