"""Google Sheets MCP tools."""

from __future__ import annotations

from typing import Any, Optional

from fastmcp import FastMCP

from ..services import sheets as sheets_svc

mcp = FastMCP("Sheets")


@mcp.tool(tags={"sheets", "read"})
def sheets_read(
    spreadsheet_id: str,
    range: str,
    profile: Optional[str] = None,
) -> dict:
    """Read data from a Google Sheet. Returns values as a 2D array.

    Args:
        spreadsheet_id: Spreadsheet ID (from the URL)
        range: A1 notation range, e.g. 'Sheet1!A1:D10' or just 'Sheet1'
        profile: Account profile name
    """
    result = sheets_svc.read(spreadsheet_id=spreadsheet_id, range=range, profile=profile)
    result["profile"] = profile or "default"
    return result


@mcp.tool(tags={"sheets", "write"})
def sheets_write(
    spreadsheet_id: str,
    range: str,
    values: list[list[Any]],
    profile: Optional[str] = None,
) -> dict:
    """Write data to a Google Sheet at a specific range. Overwrites existing data.

    Args:
        spreadsheet_id: Spreadsheet ID
        range: A1 notation range to write to
        values: 2D array of values (rows × columns)
        profile: Account profile name
    """
    result = sheets_svc.write(
        spreadsheet_id=spreadsheet_id, range=range, values=values, profile=profile,
    )
    result["profile"] = profile or "default"
    return result


@mcp.tool(tags={"sheets", "write"})
def sheets_append(
    spreadsheet_id: str,
    range: str,
    values: list[list[Any]],
    profile: Optional[str] = None,
) -> dict:
    """Append rows to the end of a Google Sheet range.

    Args:
        spreadsheet_id: Spreadsheet ID
        range: A1 notation range (appends after the last row in this range)
        values: 2D array of rows to append
        profile: Account profile name
    """
    result = sheets_svc.append(
        spreadsheet_id=spreadsheet_id, range=range, values=values, profile=profile,
    )
    result["profile"] = profile or "default"
    return result


@mcp.tool(tags={"sheets", "write"})
def sheets_create(
    title: str,
    sheet_names: Optional[list[str]] = None,
    profile: Optional[str] = None,
) -> dict:
    """Create a new Google Spreadsheet with optional named sheet tabs.

    Args:
        title: Spreadsheet title
        sheet_names: List of sheet tab names (default: ['Sheet1'])
        profile: Account profile name
    """
    result = sheets_svc.create(title=title, sheet_names=sheet_names, profile=profile)
    result["profile"] = profile or "default"
    return result


@mcp.tool(tags={"sheets", "read"})
def sheets_info(spreadsheet_id: str, profile: Optional[str] = None) -> dict:
    """Get metadata about a spreadsheet: title, sheet names, dimensions, URL.

    Args:
        spreadsheet_id: Spreadsheet ID
        profile: Account profile name
    """
    result = sheets_svc.info(spreadsheet_id=spreadsheet_id, profile=profile)
    result["profile"] = profile or "default"
    return result
