"""Discord AI agent for Sprocket (Goblin sales agent) with tool use.

Generates intelligent responses to Discord messages using Claude, with access
to the leads REST API and Anthropic's built-in web search for on-demand
lead research from Discord.
"""

from __future__ import annotations

import logging
import urllib.parse
from typing import Any

import httpx

from peon_mcp.goblin.personality import SPROCKET_DISCORD_PROMPT
from peon_mcp.grukk.discord.base_agent import BaseDiscordAgent

logger = logging.getLogger(__name__)

SPROCKET_TOOLS: list[dict[str, Any]] = [
    {
        "name": "list_leads",
        "description": "List leads for the project, optionally filtered by status.",
        "input_schema": {
            "type": "object",
            "properties": {
                "status": {
                    "type": "string",
                    "description": (
                        "Filter by status: new, researching, qualified, "
                        "outreach_ready, contacted, responded, converted, disqualified"
                    ),
                },
                "limit": {
                    "type": "integer",
                    "description": "Max results (default 20)",
                },
            },
        },
    },
    {
        "name": "get_lead",
        "description": "Get full details and enrichment data for a specific lead.",
        "input_schema": {
            "type": "object",
            "properties": {
                "lead_id": {"type": "string", "description": "Lead UUID"},
            },
            "required": ["lead_id"],
        },
    },
    {
        "name": "update_lead",
        "description": "Update a lead's status, notes, or metadata.",
        "input_schema": {
            "type": "object",
            "properties": {
                "lead_id": {"type": "string", "description": "Lead UUID"},
                "status": {
                    "type": "string",
                    "description": (
                        "New status: new, researching, qualified, "
                        "outreach_ready, contacted, responded, converted, disqualified"
                    ),
                },
                "notes": {"type": "string", "description": "Notes about the lead"},
                "metadata": {
                    "type": "object",
                    "description": "Arbitrary metadata to merge into the lead",
                },
            },
            "required": ["lead_id"],
        },
    },
    {
        "name": "lead_stats",
        "description": "Get lead counts broken down by status.",
        "input_schema": {
            "type": "object",
            "properties": {},
        },
    },
    # Anthropic's built-in web search — handled server-side, no dispatch needed.
    {
        "type": "web_search_20250305",
        "name": "web_search",
        "max_uses": 5,
    },
]


def _split_project_id(pid: str) -> tuple[str, str]:
    """Split ``owner/repo`` project ID into URL-safe path segments."""
    parts = pid.split("/", 1)
    if len(parts) == 2:
        return urllib.parse.quote(parts[0], safe=""), urllib.parse.quote(parts[1], safe="")
    return urllib.parse.quote(pid, safe=""), ""


class SprocketAgent(BaseDiscordAgent):
    """Sprocket's Discord agent — leads tools for the sales goblin."""

    def __init__(
        self,
        project_id: str,
        api_base: str = "http://127.0.0.1:8420",
        model: str = "",
        system_prompt: str = "",
        max_tool_rounds: int = 5,
    ) -> None:
        super().__init__(
            project_id=project_id,
            api_base=api_base,
            model=model,
            system_prompt=system_prompt or SPROCKET_DISCORD_PROMPT,
            max_tool_rounds=max_tool_rounds,
        )

    @property
    def tools(self) -> list[dict[str, Any]]:
        return SPROCKET_TOOLS

    async def _dispatch_tool(
        self,
        client: httpx.AsyncClient,
        name: str,
        inp: dict[str, Any],
        project_id: str = "",
    ) -> Any:
        """Route a tool call to the correct leads REST API endpoint."""
        pid = project_id or self.project_id
        base = self.api_base
        owner, repo = _split_project_id(pid)

        if not owner or not repo:
            return {"error": f"Invalid project_id '{pid}' — expected owner/repo format."}

        if name == "list_leads":
            params: dict[str, Any] = {"limit": inp.get("limit", 20)}
            if inp.get("status"):
                params["status"] = inp["status"]
            resp = await client.get(
                f"{base}/api/projects/{owner}/{repo}/leads", params=params
            )

        elif name == "get_lead":
            resp = await client.get(
                f"{base}/api/projects/{owner}/{repo}/leads/{inp['lead_id']}"
            )

        elif name == "update_lead":
            lead_id = inp.pop("lead_id")
            resp = await client.patch(
                f"{base}/api/projects/{owner}/{repo}/leads/{lead_id}", json=inp
            )

        elif name == "lead_stats":
            resp = await client.get(
                f"{base}/api/projects/{owner}/{repo}/leads/stats"
            )

        else:
            # web_search is handled server-side by Anthropic — should never reach here
            return {"error": f"Unknown tool: {name}"}

        resp.raise_for_status()
        return resp.json()
