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

from langchain_core.tools import BaseTool
from humanod import (
    HumanodClient,
    CreateTaskRequest,
    TaskCategory,
    ValidationRequest
)

class HireHumanArgs(BaseModel):
    title: str = Field(..., description="Short title of the mission (e.g. 'Take a photo of the Eiffel Tower')")
    description: str = Field(..., description="Detailed description of what needs to be done.")
    price: float = Field(..., description="Reward for the human in EUR. Must be fair and incentivize action.")
    category: str = Field(default="other", description="Category: logistics, media, inspection, or other.")
    location_name: Optional[str] = Field(None, description="Physical location where the task must be performed.")
    deliverables: str = Field(..., description="Exactly what the human must submit (e.g. '1 clear photo file').")
    validation_criteria: str = Field(..., description="How the work will be verified by the AI arbiter.")

class HireHumanTool(BaseTool):
    name: str = "hire_human"
    description: str = "Use this tool to delegate a physical or cognitive task to a real human in the real world."
    args_schema: Type[BaseModel] = HireHumanArgs
    client: HumanodClient

    def _run(
        self,
        title: str,
        description: str,
        price: float,
        deliverables: str,
        validation_criteria: str,
        category: str = "other",
        location_name: Optional[str] = None
    ) -> str:
        req = CreateTaskRequest(
            title=title,
            description=description,
            price=price,
            category=TaskCategory(category),
            location_name=location_name,
            deliverables=deliverables,
            validation_criteria=validation_criteria
        )
        task = self.client.hire_human(req)
        return f"Human hired successfully. Task ID: {task.task_id}. Payment URL (if needed): {task.payment_url}"

class CheckTaskStatusArgs(BaseModel):
    task_id: str = Field(..., description="The unique ID of the task.")

class CheckTaskStatusTool(BaseTool):
    name: str = "check_human_task_status"
    description: str = "Use this tool to check if a human has completed the assigned task."
    args_schema: Type[BaseModel] = CheckTaskStatusArgs
    client: HumanodClient

    def _run(self, task_id: str) -> str:
        status = self.client.check_task_status(task_id)
        return f"Task ID: {task_id} is currently '{status.status}'. Spots filled: {status.spots_filled}."

class HumanodToolkit:
    """
    Groups all Humanod tools for easy injection into a LangChain agent.
    """
    def __init__(self, api_key: str):
        self.client = HumanodClient(api_key=api_key)

    def get_tools(self) -> List[BaseTool]:
        return [
            HireHumanTool(client=self.client),
            CheckTaskStatusTool(client=self.client)
        ]
