"""Sheet management tools: add, delete, rename, color."""

from __future__ import annotations

import json
from typing import TYPE_CHECKING

from ironcalc_mcp.state import workbook

if TYPE_CHECKING:
    from mcp.server.fastmcp import FastMCP


def register(server: FastMCP) -> None:
    @server.tool()
    async def add_sheet(name: str | None = None) -> str:
        """Add a new sheet to the workbook.

        Args:
            name: Optional sheet name. If omitted, auto-named (Sheet2, Sheet3, etc.)
        """
        if name:
            workbook.model.add_sheet(name)
        else:
            workbook.model.new_sheet()
        workbook.model.evaluate()
        sheets = workbook.get_sheets()
        return json.dumps({
            "status": "added",
            "sheets": [{"index": s.index, "name": s.name} for s in sheets],
        })

    @server.tool()
    async def delete_sheet(sheet: int) -> str:
        """Delete a sheet by index.

        Args:
            sheet: Sheet index (0-based)
        """
        workbook.model.delete_sheet(sheet)
        workbook.model.evaluate()
        sheets = workbook.get_sheets()
        return json.dumps({
            "status": "deleted",
            "sheets": [{"index": s.index, "name": s.name} for s in sheets],
        })

    @server.tool()
    async def rename_sheet(sheet: int, name: str) -> str:
        """Rename a sheet.

        Args:
            sheet: Sheet index (0-based)
            name: New sheet name
        """
        workbook.model.rename_sheet(sheet, name)
        return json.dumps({"status": "renamed", "sheet": sheet, "name": name})

    @server.tool()
    async def set_sheet_color(sheet: int, color: str) -> str:
        """Set the tab color of a sheet.

        Args:
            sheet: Sheet index (0-based)
            color: Hex color string (e.g. '#FF0000')
        """
        workbook.model.set_sheet_color(sheet, color)
        return json.dumps({"status": "ok", "sheet": sheet, "color": color})
