"""Cell read/write tools."""

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 get_cell(sheet: int, row: int, column: int) -> str:
        """Get a single cell's content, formatted value, and type.

        Args:
            sheet: Sheet index (0-based)
            row: Row number (1-based)
            column: Column number (1-based)
        """
        cell = workbook.get_cell(sheet, row, column)
        return json.dumps({
            "row": cell.row,
            "column": cell.column,
            "content": cell.content,
            "formatted": cell.formatted,
            "type": cell.cell_type,
        })

    @server.tool()
    async def get_cells(
        sheet: int,
        row_start: int,
        col_start: int,
        row_end: int,
        col_end: int,
    ) -> str:
        """Get cells in a rectangular range.

        Args:
            sheet: Sheet index (0-based)
            row_start: First row (1-based)
            col_start: First column (1-based)
            row_end: Last row (1-based, inclusive)
            col_end: Last column (1-based, inclusive)
        """
        cells = workbook.get_cells_in_range(sheet, row_start, col_start, row_end, col_end)
        return json.dumps([
            {
                "row": c.row,
                "column": c.column,
                "content": c.content,
                "formatted": c.formatted,
                "type": c.cell_type,
            }
            for c in cells
        ])

    @server.tool()
    async def set_cell(sheet: int, row: int, column: int, value: str) -> str:
        """Set a single cell's value. Use '=' prefix for formulas.

        Args:
            sheet: Sheet index (0-based)
            row: Row number (1-based)
            column: Column number (1-based)
            value: Cell value (text, number, or formula starting with '=')
        """
        workbook.set_cell(sheet, row, column, value)
        cell = workbook.get_cell(sheet, row, column)
        return json.dumps({
            "row": row,
            "column": column,
            "content": cell.content,
            "formatted": cell.formatted,
            "type": cell.cell_type,
        })

    @server.tool()
    async def set_cells(cells: list[dict]) -> str:
        """Set multiple cells in batch. Each entry needs sheet, row, column, value.

        Args:
            cells: List of {sheet: int, row: int, column: int, value: str}
        """
        count = workbook.set_cells_batch(cells)
        return json.dumps({"status": "ok", "cells_set": count})
