"""Bounding box generation tool handler.

This module provides the handler for generating bounding box
GDS files from input GDS files.
"""

from __future__ import annotations

from typing import Any

from mcp.types import Tool

from .base import EndpointMapping, ToolHandler, add_project_param

__all__ = ["GenerateBboxHandler"]


class GenerateBboxHandler(ToolHandler):
    """Handler for generating bounding box GDS files.

    Creates a simplified version of the layout with only a bounding box
    on specified layers.
    """

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

    @property
    def definition(self) -> Tool:
        return Tool(
            name="generate_bbox",
            description=(
                "Generate a bounding box GDS file from an input GDS. This creates "
                "a simplified version of the layout with only a bounding box on "
                "specified layers. Useful for creating abstract views, floorplanning, "
                "or hierarchical design. Can optionally preserve specific layers and "
                "ports."
            ),
            inputSchema=add_project_param(
                {
                    "type": "object",
                    "properties": {
                        "path": {
                            "type": "string",
                            "description": (
                                "Path to the input GDS file. Can be absolute or relative "
                                "to the project directory."
                            ),
                        },
                        "outpath": {
                            "type": "string",
                            "description": (
                                "Output path for the bounding box GDS. If not specified, "
                                "uses the input filename with '-bbox' suffix."
                            ),
                            "default": "",
                        },
                        "layers_to_keep": {
                            "type": "array",
                            "items": {"type": "string"},
                            "description": (
                                "List of layer names to preserve in the output. "
                                "Other layers will be replaced by the bounding box."
                            ),
                            "default": [],
                        },
                        "bbox_layer": {
                            "type": "array",
                            "items": {"type": "integer"},
                            "description": (
                                "Layer (as [layer, datatype]) to use for the bounding box. "
                                "Default is [99, 0]."
                            ),
                            "default": [99, 0],
                        },
                        "ignore_ports": {
                            "type": "boolean",
                            "description": (
                                "If true, do not include ports in the output. "
                                "Default is false."
                            ),
                            "default": False,
                        },
                    },
                    "required": ["path"],
                }
            ),
        )

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

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

        Args:
            args: MCP tool arguments

        Returns:
            Dict with 'json_data' key for request body
        """
        json_data: dict[str, Any] = {"path": args["path"]}

        if "outpath" in args and args["outpath"]:
            json_data["outpath"] = args["outpath"]
        if "layers_to_keep" in args and args["layers_to_keep"]:
            json_data["layers_to_keep"] = args["layers_to_keep"]
        if "bbox_layer" in args and args["bbox_layer"]:
            json_data["bbox_layer"] = args["bbox_layer"]
        if "ignore_ports" in args:
            json_data["ignore_ports"] = args["ignore_ports"]

        return {"json_data": json_data}
