"""Account tools (read scope required)."""

from __future__ import annotations

from typing import Any

from mcp.server.fastmcp import Context
from mcp.types import ToolAnnotations

from liquidtrading.errors import LiquidError
from liquid_mcp.client_manager import get_client
from liquid_mcp.config import get_config
from liquid_mcp.error_handling import handle_sdk_error
from liquid_mcp.serializers import to_dict
from liquid_mcp.server import mcp


@mcp.tool(annotations=ToolAnnotations(readOnlyHint=True))
def get_account(ctx: Context) -> dict[str, Any]:
    """Get account overview: equity, margin, available balance."""
    try:
        client = get_client(get_config())
        account = client.get_account()
    except LiquidError as e:
        return handle_sdk_error("get_account", e)

    return {
        **to_dict(account),
        "next_steps": ["get_positions", "get_balances", "calculate_position_size"],
    }


@mcp.tool(annotations=ToolAnnotations(readOnlyHint=True))
def get_balances(ctx: Context) -> dict[str, Any]:
    """Get detailed balance breakdown including cross margin info."""
    try:
        client = get_client(get_config())
        balances = client.get_balances()
    except LiquidError as e:
        return handle_sdk_error("get_balances", e)

    return {
        **to_dict(balances),
        "next_steps": ["get_account", "get_positions"],
    }


@mcp.tool(annotations=ToolAnnotations(readOnlyHint=True))
def get_positions(ctx: Context) -> dict[str, Any]:
    """Get all open positions with PnL, leverage, and liquidation prices."""
    try:
        client = get_client(get_config())
        positions = client.get_positions()
    except LiquidError as e:
        return handle_sdk_error("get_positions", e)

    return {
        "positions": to_dict(positions),
        "next_steps": ["set_tp_sl", "close_position", "update_leverage"],
    }
