"""
LangChain integration for Loopuman

Usage:
    from loopuman.langchain_tool import LoopumanTool
    
    tool = LoopumanTool(api_key="your_key")
    agent = initialize_agent([tool], llm)
"""

import os
from typing import Optional

try:
    from langchain.tools import BaseTool
    from pydantic import Field
except ImportError:
    raise ImportError("langchain is required: pip install langchain")

from . import Loopuman

class LoopumanTool(BaseTool):
    """LangChain tool that gives agents access to human workers."""
    
    name: str = "ask_human"
    description: str = """Ask a human worker to help with a task. 
Use this tool when you need:
- Verification of facts or content
- Subjective judgment (is this appropriate, offensive, accurate?)
- Real-world information (what's at this location?)
- Human oversight for important decisions

Input should be a clear question or task description.
Returns the human's response as a string."""
    
    client: Loopuman = Field(default=None, exclude=True)
    budget_cents: int = 50
    timeout_seconds: int = 300
    
    def __init__(self, api_key: Optional[str] = None, **kwargs):
        super().__init__(**kwargs)
        key = api_key or os.environ.get("LOOPUMAN_API_KEY")
        if not key:
            raise ValueError("LOOPUMAN_API_KEY required")
        self.client = Loopuman(api_key=key)
    
    def _run(self, query: str) -> str:
        """Execute the tool."""
        result = self.client.ask(
            question=query,
            budget_cents=self.budget_cents,
            timeout_seconds=self.timeout_seconds
        )
        
        if result.status == "completed":
            return result.response
        return f"No human responded within {self.timeout_seconds}s. Task ID: {result.task_id}"
    
    async def _arun(self, query: str) -> str:
        """Async not implemented yet."""
        return self._run(query)
