"""SiliconBridge tools for CrewAI agents."""

import time
import httpx
from typing import Type
from pydantic import BaseModel, Field
from crewai.tools import BaseTool


SILICONBRIDGE_BASE_URL = "https://siliconbridge.xyz"


def _submit_and_wait(api_key: str, service_type: str, payload: dict, timeout: int = 300) -> str:
    headers = {"X-API-Key": api_key, "Content-Type": "application/json"}
    with httpx.Client(timeout=30.0) as client:
        r = client.post(
            f"{SILICONBRIDGE_BASE_URL}/tasks/submit",
            headers=headers,
            json={"service_type": service_type, "payload": payload},
        )
        r.raise_for_status()
        task_id = r.json()["task_id"]

        deadline = time.time() + timeout
        while time.time() < deadline:
            r = client.get(f"{SILICONBRIDGE_BASE_URL}/tasks/{task_id}", headers=headers)
            r.raise_for_status()
            data = r.json()
            if data["status"] == "completed":
                return str(data.get("result", {}).get("solution", data.get("result", "")))
            if data["status"] == "failed":
                return f"Task failed: {data.get('result', 'unknown error')}"
            time.sleep(5)
        return f"Task {task_id} timed out after {timeout}s"


class CaptchaSolveInput(BaseModel):
    image_url: str = Field(description="URL of the CAPTCHA image")


class SiliconBridgeCaptchaSolver(BaseTool):
    name: str = "SiliconBridge CAPTCHA Solver"
    description: str = (
        "Solves CAPTCHAs by sending them to a real human operator. "
        "Use when you encounter a CAPTCHA blocking your progress."
    )
    args_schema: Type[BaseModel] = CaptchaSolveInput
    api_key: str = ""

    def _run(self, image_url: str) -> str:
        return _submit_and_wait(self.api_key, "captcha_solve", {"image_url": image_url})


class CustomTaskInput(BaseModel):
    instructions: str = Field(description="What the human operator should do")


class SiliconBridgeHumanTask(BaseTool):
    name: str = "SiliconBridge Human Task"
    description: str = (
        "Sends any task to a real human operator. "
        "Use when you need human help: reading handwriting, verifying info, making judgment calls."
    )
    args_schema: Type[BaseModel] = CustomTaskInput
    api_key: str = ""

    def _run(self, instructions: str) -> str:
        return _submit_and_wait(self.api_key, "custom", {"instructions": instructions})


class ContentModerateInput(BaseModel):
    content: str = Field(description="Content to moderate")
    guidelines: str = Field(default="Flag hate speech, spam, or adult content")


class SiliconBridgeModerator(BaseTool):
    name: str = "SiliconBridge Content Moderator"
    description: str = "Sends content to a human moderator for review."
    args_schema: Type[BaseModel] = ContentModerateInput
    api_key: str = ""

    def _run(self, content: str, guidelines: str = "Flag hate speech, spam, or adult content") -> str:
        return _submit_and_wait(self.api_key, "content_moderate", {"content": content, "guidelines": guidelines})


def get_siliconbridge_tools(api_key: str) -> list:
    """
    Returns all SiliconBridge tools for CrewAI.

    Usage:
        from siliconbridge.integrations.crewai_tool import get_siliconbridge_tools
        tools = get_siliconbridge_tools("sb_your_key")
        agent = Agent(tools=tools, ...)
    """
    return [
        SiliconBridgeCaptchaSolver(api_key=api_key),
        SiliconBridgeHumanTask(api_key=api_key),
        SiliconBridgeModerator(api_key=api_key),
    ]
