"""Structured error handling for MCP tool responses."""

from __future__ import annotations

from typing import Any

from liquidtrading.errors import (
    AuthenticationError,
    ConnectionError as LiquidConnectionError,
    InsufficientBalanceError,
    LiquidError,
    OrderRejectedError,
    RateLimitError,
    SymbolNotFoundError,
    TimeoutError as LiquidTimeoutError,
)


def handle_sdk_error(tool_name: str, error: LiquidError) -> dict[str, Any]:
    """Convert an SDK exception into a structured error response for the LLM.

    Returns a dict with error info and actionable next_steps so the LLM
    can recover instead of seeing a raw traceback.
    """
    base: dict[str, Any] = {
        "error": True,
        "error_code": error.code,
        "message": error.message,
        "tool": tool_name,
    }

    if isinstance(error, SymbolNotFoundError):
        return {
            **base,
            "hint": "Symbol not found. Call get_markets to list valid symbols.",
            "next_steps": ["get_markets"],
        }

    if isinstance(error, InsufficientBalanceError):
        return {
            **base,
            "hint": "Insufficient balance. Check available balance with get_account.",
            "next_steps": ["get_account", "get_balances"],
        }

    if isinstance(error, OrderRejectedError):
        return {
            **base,
            "hint": "Order was rejected by the exchange. Check position and order params.",
            "next_steps": ["get_positions", "validate_trade"],
        }

    if isinstance(error, RateLimitError):
        retry = error.retry_after
        hint = "Rate limited."
        if retry is not None:
            hint += f" Wait {retry:.0f}s before retrying."
        else:
            hint += " Wait a few seconds before retrying."
        return {**base, "hint": hint, "retry_after": retry, "next_steps": []}

    if isinstance(error, AuthenticationError):
        return {
            **base,
            "hint": "Authentication failed. Check API key and secret configuration.",
            "next_steps": [],
        }

    if isinstance(error, (LiquidTimeoutError, LiquidConnectionError)):
        return {
            **base,
            "hint": "Network issue. The request may have succeeded — check state before retrying.",
            "next_steps": ["get_positions", "get_open_orders"],
        }

    # Fallback for any other LiquidError
    return {
        **base,
        "hint": f"Unexpected error: {error.message}",
        "next_steps": [],
    }
