"""Project discovery tool handlers.

These tools handle project listing and info retrieval from the
server registry without making HTTP requests to the backend.
"""

from __future__ import annotations

import json
import logging
from typing import TYPE_CHECKING, Any

from mcp.types import TextContent, Tool

from .base import EndpointMapping, ToolHandler

if TYPE_CHECKING:
    from ..client import FastAPIClient

__all__ = ["ListProjectsHandler", "GetProjectInfoHandler"]

logger = logging.getLogger(__name__)


class ListProjectsHandler(ToolHandler):
    """Handler for listing all active GDSFactory+ projects.

    This is a registry-only tool that doesn't make HTTP requests.
    It reads from the local server registry to discover running servers.
    """

    @property
    def name(self) -> str:
        return "list_projects"

    @property
    def definition(self) -> Tool:
        return Tool(
            name="list_projects",
            description=(
                "List all active GDSFactory+ projects. Returns information about "
                "all running servers including project name, path, port, PID, and PDK. "
                "Use this to discover which projects are available for interaction."
            ),
            inputSchema={
                "type": "object",
                "properties": {},
            },
        )

    @property
    def mapping(self) -> EndpointMapping | None:
        # Registry-only tool, no HTTP endpoint
        return None

    async def handle(
        self,
        arguments: dict[str, Any],
        client: FastAPIClient,
    ) -> list[TextContent]:
        """List all projects from the registry.

        Args:
            arguments: MCP tool arguments (unused for this tool)
            client: FastAPI client (used to access registry)

        Returns:
            List containing TextContent with project list
        """
        try:
            projects = client.list_projects()
            return [
                TextContent(
                    type="text",
                    text=json.dumps({"projects": projects}, indent=2),
                )
            ]
        except Exception as e:
            error_msg = f"Failed to list projects: {e!s}"
            logger.exception(error_msg)
            return [TextContent(type="text", text=json.dumps({"error": error_msg}))]


class GetProjectInfoHandler(ToolHandler):
    """Handler for getting detailed info about a specific project.

    This tool makes an HTTP request to the project's /info endpoint
    to retrieve detailed information including version and PDK details.
    """

    @property
    def name(self) -> str:
        return "get_project_info"

    @property
    def definition(self) -> Tool:
        return Tool(
            name="get_project_info",
            description=(
                "Get detailed information about a specific project. Returns metadata "
                "including project name, path, port, PID, PDK, and version. "
                "Use this to get information about a running project."
            ),
            inputSchema={
                "type": "object",
                "properties": {
                    "project": {
                        "type": "string",
                        "description": (
                            "Project name or path. Can be the project directory name "
                            "or full path."
                        ),
                    },
                },
                "required": ["project"],
            },
        )

    @property
    def mapping(self) -> EndpointMapping:
        return EndpointMapping(method="GET", path="/info")

    def transform_request(self, args: dict[str, Any]) -> dict[str, Any]:
        """No request transformation needed - just routes to /info."""
        return {}

    async def handle(
        self,
        arguments: dict[str, Any],
        client: FastAPIClient,
    ) -> list[TextContent]:
        """Get project info via HTTP request.

        Args:
            arguments: MCP tool arguments with 'project' key
            client: FastAPI client for making requests

        Returns:
            List containing TextContent with project info
        """
        try:
            project = arguments.get("project")
            if not project:
                return [
                    TextContent(
                        type="text",
                        text=json.dumps({"error": "project parameter is required"}),
                    )
                ]

            response = await client.request(
                method="GET",
                path="/info",
                project=project,
            )
            return [TextContent(type="text", text=json.dumps(response, indent=2))]
        except Exception as e:
            error_msg = f"Failed to get project info: {e!s}"
            logger.exception(error_msg)
            return [TextContent(type="text", text=json.dumps({"error": error_msg}))]
