"""Build cells tool handler.

This module provides the handler for building GDS cells, including
optional PNG image rendering for visualization.
"""

from __future__ import annotations

import json
import logging
from typing import TYPE_CHECKING, Any

from mcp.types import ImageContent, TextContent, Tool

from ..render import HAS_KLAYOUT, render_built_cells
from .base import EndpointMapping, ToolHandler, add_project_param

if TYPE_CHECKING:
    from ..client import FastAPIClient

__all__ = ["BuildCellsHandler"]

logger = logging.getLogger(__name__)


class BuildCellsHandler(ToolHandler):
    """Handler for building GDS cells.

    This handler builds one or more GDS cells and optionally renders
    specified cells to PNG images for visualization.
    """

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

    @property
    def definition(self) -> Tool:
        return Tool(
            name="build_cells",
            description=(
                "Build one or more GDS cells by name. This creates the physical layout "
                "files (.gds) for photonic components. Pass a list of cell names to build. "
                "For a single cell, pass a list with one element. All cells are built "
                "in the background and saved to the project build directory. "
                "Use the optional 'visualize' parameter to specify which cells should be "
                "rendered to PNG images and returned in the response."
            ),
            inputSchema=add_project_param(
                {
                    "type": "object",
                    "properties": {
                        "names": {
                            "type": "array",
                            "items": {"type": "string"},
                            "description": "List of cell/component names to build (can be a single-item list)",
                        },
                        "visualize": {
                            "type": "array",
                            "items": {"type": "string"},
                            "description": (
                                "Optional list of cell names to render as PNG images. "
                                "Only cells in this list will be visualized. If not provided, "
                                "no images are returned. Use this to selectively view only "
                                "the cells you need to inspect."
                            ),
                        },
                        "with_metadata": {
                            "type": "boolean",
                            "description": (
                                "Include metadata in the GDS files (default: true)"
                            ),
                            "default": True,
                        },
                        "register": {
                            "type": "boolean",
                            "description": (
                                "Re-register the cells in the KLayout cache (default: true)"
                            ),
                            "default": True,
                        },
                    },
                    "required": ["names"],
                }
            ),
        )

    @property
    def mapping(self) -> EndpointMapping:
        return EndpointMapping(method="POST", path="/api/build-cells")

    def transform_request(self, args: dict[str, Any]) -> dict[str, Any]:
        """Transform build_cells MCP args to FastAPI params.

        Args:
            args: MCP tool arguments

        Returns:
            Dict with 'params' key for query parameters and 'json_data' for body
        """
        return {
            "params": {
                "with_metadata": args.get("with_metadata", True),
                "register": args.get("register", True),
            },
            "json_data": args["names"],
        }

    async def handle(
        self,
        arguments: dict[str, Any],
        client: FastAPIClient,
    ) -> list[TextContent | ImageContent]:
        """Build cells and optionally render images.

        Args:
            arguments: MCP tool arguments
            client: FastAPI client for making requests

        Returns:
            List of TextContent with build results and optional ImageContent
        """
        try:
            project = arguments.get("project")
            transformed = self.transform_request(arguments)

            response = await client.request(
                method=self.mapping.method,
                path=self.mapping.path,
                params=transformed.get("params"),
                json_data=transformed.get("json_data"),
                project=project,
            )

            logger.debug("Build cells result: %s", response)

            results: list[TextContent | ImageContent] = [
                TextContent(
                    type="text",
                    text=json.dumps(response, indent=2),
                )
            ]

            # Render images if klayout is available and visualize is specified
            visualize = arguments.get("visualize", [])
            if visualize and HAS_KLAYOUT:
                results.extend(await render_built_cells(visualize, project))

            return results

        except Exception as e:
            error_msg = f"Tool execution failed: {e!s}"
            logger.exception(error_msg)
            return [
                TextContent(
                    type="text",
                    text=json.dumps({"error": error_msg}),
                )
            ]
