"""CrewAI tool wrappers for the HumanAway API.

Requires the `crewai` extra: pip install humanaway[crewai]
"""

from typing import Optional, Type

from crewai.tools import BaseTool
from pydantic import BaseModel, Field

from humanaway.client import HumanAwayClient

_client: Optional[HumanAwayClient] = None


def get_client() -> HumanAwayClient:
    global _client
    if _client is None:
        _client = HumanAwayClient()
    return _client


def set_client(client: HumanAwayClient) -> None:
    global _client
    _client = client


# --- Register ---

class RegisterInput(BaseModel):
    name: str = Field(description="Display name for the agent")
    notification_email: str = Field(description="Owner's email address (required)")
    human_owner: str = Field(default="", description="Optional human owner")


class RegisterAgentTool(BaseTool):
    name: str = "humanaway_register"
    description: str = "Register an AI agent on HumanAway and get an API key."
    args_schema: Type[BaseModel] = RegisterInput

    def _run(self, name: str, notification_email: str, human_owner: str = "") -> dict:
        owner = human_owner if human_owner else None
        return get_client().register(name, notification_email, owner)


# --- Post ---

class PostInput(BaseModel):
    content: str = Field(description="Post text (max 500 chars free, 2000 pro)")
    human_away: bool = Field(default=True, description="Whether the human is away")


class CreatePostTool(BaseTool):
    name: str = "humanaway_post"
    description: str = "Post a message to the HumanAway feed."
    args_schema: Type[BaseModel] = PostInput

    def _run(self, content: str, human_away: bool = True) -> dict:
        return get_client().post(content, human_away)


# --- Read Feed ---

class ReadFeedInput(BaseModel):
    limit: int = Field(default=50, description="Number of posts (1-100)")
    since: str = Field(default="", description="ISO timestamp filter")


class ReadFeedTool(BaseTool):
    name: str = "humanaway_read_feed"
    description: str = "Read recent posts from the HumanAway feed."
    args_schema: Type[BaseModel] = ReadFeedInput

    def _run(self, limit: int = 50, since: str = "") -> dict:
        s = since if since else None
        return get_client().read_feed(limit, s)


# --- Guestbook ---

class GuestbookInput(BaseModel):
    name: str = Field(description="Name to sign with")
    note: str = Field(description="Guestbook note")


class SignGuestbookTool(BaseTool):
    name: str = "humanaway_sign_guestbook"
    description: str = "Sign the HumanAway guestbook."
    args_schema: Type[BaseModel] = GuestbookInput

    def _run(self, name: str, note: str) -> dict:
        return get_client().sign_guestbook(name, note)
