/**
 * MCP Tools Index
 *
 * Exports all Binance MCP tools and their schemas for registration
 *
 * @version 1.0.0
 * @author Trading Platform Trading Platform
 */

// Import handlers for use in toolHandlers map
import { handleBinanceGetTicker, handleBinanceGetOrderbook, handleBinanceGetKlines } from './market';
import { handleBinanceGetAccount, handleBinanceGetOpenOrders } from './account';
import { handleBinanceCreateOrder, handleBinanceCancelOrder } from './orders';

// ==========================================
// Market Tools Exports
// ==========================================

export {
  binanceGetTickerSchema,
  binance_get_ticker,
  handleBinanceGetTicker,
  BinanceGetTickerInputSchema,
  type BinanceGetTickerInput,
  type BinanceGetTickerResult,
  binanceGetOrderbookSchema,
  binance_get_orderbook,
  handleBinanceGetOrderbook,
  BinanceGetOrderbookInputSchema,
  type BinanceGetOrderbookInput,
  type BinanceGetOrderbookResult,
  binanceGetKlinesSchema,
  binance_get_klines,
  handleBinanceGetKlines,
  BinanceGetKlinesInputSchema,
  type BinanceGetKlinesInput,
  type BinanceGetKlinesResult,
} from './market';

// ==========================================
// Account Tools Exports
// ==========================================

export {
  binanceGetAccountSchema,
  binance_get_account,
  handleBinanceGetAccount,
  BinanceGetAccountInputSchema,
  type BinanceGetAccountInput,
  type BinanceGetAccountResult,
  binanceGetOpenOrdersSchema,
  binance_get_open_orders,
  handleBinanceGetOpenOrders,
  BinanceGetOpenOrdersInputSchema,
  type BinanceGetOpenOrdersInput,
  type BinanceGetOpenOrdersResult,
} from './account';

// ==========================================
// Order Tools Exports
// ==========================================

export {
  binanceCreateOrderSchema,
  binance_create_order,
  handleBinanceCreateOrder,
  BinanceCreateOrderInputSchema,
  type BinanceCreateOrderInput,
  type BinanceCreateOrderResult,
  binanceCancelOrderSchema,
  binance_cancel_order,
  handleBinanceCancelOrder,
  BinanceCancelOrderInputSchema,
  type BinanceCancelOrderInput,
  type BinanceCancelOrderResult,
} from './orders';

// ==========================================
// Tool Registry
// ==========================================

/**
 * All available MCP tools with their schemas
 * Follows MCP protocol format
 */
export const mcpToolSchemas = [
  // Market Data Tools (Low Risk)
  {
    name: 'binance_get_ticker',
    description: 'Get the current price and 24-hour statistics for a Binance trading pair',
    inputSchema: {
      type: 'object' as const,
      properties: {
        symbol: {
          type: 'string',
          description: 'Trading pair symbol (e.g., BTCUSDT, ETHUSDT, BNBUSDT)',
        },
      },
      required: ['symbol'] as string[],
    },
    riskLevel: 'LOW',
  },
  {
    name: 'binance_get_orderbook',
    description: 'Get the order book (bids and asks) with the specified depth for a trading pair',
    inputSchema: {
      type: 'object' as const,
      properties: {
        symbol: {
          type: 'string',
          description: 'Trading pair symbol (e.g., BTCUSDT)',
        },
        limit: {
          type: 'number',
          description: 'Order book depth (5, 10, 20, 50, or 100). Default: 20',
        },
      },
      required: ['symbol'] as string[],
    },
    riskLevel: 'LOW',
  },
  {
    name: 'binance_get_klines',
    description: 'Get historical candlestick (OHLCV) data for technical analysis',
    inputSchema: {
      type: 'object' as const,
      properties: {
        symbol: {
          type: 'string',
          description: 'Trading pair symbol (e.g., BTCUSDT)',
        },
        interval: {
          type: 'string',
          description: 'Candle interval: 1m, 5m, 15m, 30m, 1h, 4h, 1d, 1w. Default: 5m',
          enum: ['1m', '5m', '15m', '30m', '1h', '4h', '1d', '1w'],
        },
        limit: {
          type: 'number',
          description: 'Number of candles to retrieve (max 500). Default: 100',
        },
      },
      required: ['symbol'] as string[],
    },
    riskLevel: 'LOW',
  },

  // Account Tools (Medium Risk)
  {
    name: 'binance_get_account',
    description: 'Get Binance account balance and status. Shows all assets with non-zero balance.',
    inputSchema: {
      type: 'object' as const,
      properties: {},
      required: [] as string[],
    },
    riskLevel: 'MEDIUM',
  },
  {
    name: 'binance_get_open_orders',
    description: 'Get all open (pending) orders. Optionally filter by symbol.',
    inputSchema: {
      type: 'object' as const,
      properties: {
        symbol: {
          type: 'string',
          description: 'Optional: Filter by trading pair symbol (e.g., BTCUSDT)',
        },
      },
      required: [] as string[],
    },
    riskLevel: 'MEDIUM',
  },

  // Order Tools (High Risk)
  {
    name: 'binance_create_order',
    description: 'Create a new buy or sell order on Binance. HIGH RISK - Ensure you validate with the user before executing.',
    inputSchema: {
      type: 'object' as const,
      properties: {
        symbol: {
          type: 'string',
          description: 'Trading pair symbol (e.g., BTCUSDT, ETHUSDT)',
        },
        side: {
          type: 'string',
          enum: ['buy', 'sell'],
          description: 'Order direction: buy or sell',
        },
        type: {
          type: 'string',
          enum: ['market', 'limit', 'stop_loss', 'take_profit'],
          description: 'Order type. Default: market',
        },
        amount: {
          type: 'number',
          description: 'Amount of the base asset to buy/sell',
        },
        price: {
          type: 'number',
          description: 'Price per unit (required for limit orders)',
        },
        stopPrice: {
          type: 'number',
          description: 'Stop price (required for stop_loss and take_profit orders)',
        },
      },
      required: ['symbol', 'side', 'amount'] as string[],
    },
    riskLevel: 'HIGH',
    requiresConfirmation: true,
  },
  {
    name: 'binance_cancel_order',
    description: 'Cancel a pending order by order ID and symbol',
    inputSchema: {
      type: 'object' as const,
      properties: {
        symbol: {
          type: 'string',
          description: 'Trading pair symbol (e.g., BTCUSDT)',
        },
        orderId: {
          type: 'string',
          description: 'Order ID to cancel',
        },
      },
      required: ['symbol', 'orderId'] as string[],
    },
    riskLevel: 'MEDIUM',
  },
];

/**
 * Tool handler routing map
 * Maps tool names to their handler functions
 */
export const toolHandlers: Record<
  string,
  (params: unknown) => Promise<{ content: Array<{ type: string; text: string }> }>
> = {
  // Market tools
  binance_get_ticker: handleBinanceGetTicker,
  binance_get_orderbook: handleBinanceGetOrderbook,
  binance_get_klines: handleBinanceGetKlines,

  // Account tools
  binance_get_account: handleBinanceGetAccount,
  binance_get_open_orders: handleBinanceGetOpenOrders,

  // Order tools
  binance_create_order: handleBinanceCreateOrder,
  binance_cancel_order: handleBinanceCancelOrder,
};

/**
 * Get all tool definitions for MCP protocol
 */
export function getAllToolDefinitions() {
  return mcpToolSchemas.map((tool) => ({
    name: tool.name,
    description: tool.description,
    inputSchema: tool.inputSchema,
  }));
}

/**
 * Get tool by name
 */
export function getToolByName(name: string) {
  return mcpToolSchemas.find((tool) => tool.name === name);
}

/**
 * Check if a tool requires confirmation
 */
export function toolRequiresConfirmation(name: string): boolean {
  const tool = mcpToolSchemas.find((t) => t.name === name);
  return (tool as { requiresConfirmation?: boolean })?.requiresConfirmation === true;
}

/**
 * Get tool risk level
 */
export function getToolRiskLevel(name: string): string {
  const tool = mcpToolSchemas.find((t) => t.name === name);
  return (tool as { riskLevel?: string })?.riskLevel ?? 'UNKNOWN';
}
