"""Cell formatting/style 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 _style_to_dict(style) -> dict:
    """Convert a PyStyle to a JSON-serializable dict."""
    result: dict = {
        "num_fmt": style.num_fmt,
        "quote_prefix": style.quote_prefix,
    }

    font = style.font
    result["font"] = {
        "name": font.name,
        "size": font.sz,
        "bold": font.b,
        "italic": font.i,
        "underline": font.u,
        "strikethrough": font.strike,
        "color": font.color,
    }

    fill = style.fill
    result["fill"] = {
        "pattern_type": fill.pattern_type,
        "fg_color": fill.fg_color,
        "bg_color": fill.bg_color,
    }

    if style.alignment:
        a = style.alignment
        result["alignment"] = {
            "horizontal": a.horizontal.name,
            "vertical": a.vertical.name,
            "wrap_text": a.wrap_text,
        }

    return result


def register(server: FastMCP) -> None:
    @server.tool()
    async def get_cell_style(sheet: int, row: int, column: int) -> str:
        """Get the style (font, fill, border, alignment, number format) of a cell.

        Args:
            sheet: Sheet index (0-based)
            row: Row number (1-based)
            column: Column number (1-based)
        """
        style = workbook.model.get_cell_style(sheet, row, column)
        return json.dumps(_style_to_dict(style))

    # NOTE: set_cell_style is not available because the IronCalc Python binding
    # exposes PyStyle/PyFont properties as read-only. This needs #[pyo3(get, set)]
    # in the Rust binding to work. Track: https://github.com/ironcalc/IronCalc/issues
