"""Market data tools (read scope required on the hosted Liquid API)."""

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.guardrails import min_order_info
from liquid_mcp.serializers import to_dict
from liquid_mcp.server import mcp


@mcp.tool(annotations=ToolAnnotations(readOnlyHint=True))
def get_markets(ctx: Context) -> dict[str, Any]:
    """List all tradeable markets on Liquid.

    Call this first to discover valid symbols before using other tools.
    """
    try:
        client = get_client(get_config())
        markets = client.get_markets()
    except LiquidError as e:
        return handle_sdk_error("get_markets", e)

    return {"markets": markets, "next_steps": ["get_ticker", "get_orderbook"]}


@mcp.tool(annotations=ToolAnnotations(readOnlyHint=True))
def get_ticker(symbol: str, ctx: Context) -> dict[str, Any]:
    """Get 24h ticker for a symbol (price, volume, funding rate).

    Args:
        symbol: Trading pair symbol, e.g. "BTC-PERP". Call get_markets to list valid symbols.
    """
    try:
        client = get_client(get_config())
        ticker = client.get_ticker(symbol)
    except LiquidError as e:
        return handle_sdk_error("get_ticker", e)

    return {
        **to_dict(ticker),
        "min_order": min_order_info(ticker.mark_price),
        "next_steps": ["get_orderbook", "place_order", "calculate_position_size"],
    }


@mcp.tool(annotations=ToolAnnotations(readOnlyHint=True))
def get_orderbook(symbol: str, depth: int = 20, ctx: Context = None) -> dict[str, Any]:
    """Get L2 order book for a symbol.

    Args:
        symbol: Trading pair symbol, e.g. "BTC-PERP". Call get_markets to list valid symbols.
        depth: Number of price levels per side (default 20)
    """
    try:
        client = get_client(get_config())
        book = client.get_orderbook(symbol, depth=depth)
    except LiquidError as e:
        return handle_sdk_error("get_orderbook", e)

    return {
        **to_dict(book),
        "next_steps": ["get_ticker", "place_order", "calculate_token_amount"],
    }


@mcp.tool(annotations=ToolAnnotations(readOnlyHint=True))
def get_candles(
    symbol: str,
    interval: str = "1h",
    limit: int = 100,
    start: int | None = None,
    end: int | None = None,
    ctx: Context = None,
) -> dict[str, Any]:
    """Get OHLCV candle data for a symbol.

    Args:
        symbol: Trading pair symbol, e.g. "BTC-PERP". Call get_markets to list valid symbols.
        interval: Candle interval: 1m, 5m, 15m, 30m, 1h, 4h, 1d
        limit: Max candles to return (default 100)
        start: Optional start time as Unix timestamp (seconds), inclusive
        end: Optional end time as Unix timestamp (seconds), inclusive
    """
    try:
        client = get_client(get_config())
        candles = client.get_candles(
            symbol, interval=interval, limit=limit, start=start, end=end,
        )
    except LiquidError as e:
        return handle_sdk_error("get_candles", e)

    return {
        "symbol": symbol,
        "interval": interval,
        "candles": to_dict(candles),
        "next_steps": ["get_ticker", "place_order", "validate_trade"],
    }
