const { Plugin } = require('../src/core/plugin-base')
class GateTradingPlugin extends Plugin {
  constructor(config = {}) {
    super();
    this.name = 'gate-trading';
    this.version = '1.1.0';
    this.description = 'Gate.io 加密货币交易插件（支持现货+合约）';
    this.priority = 100;
    
    // 从 .env 文件读取密钥
    const fs = require('fs');
    const path = require('path');
    this.apiKey = config.apiKey || process.env.GATE_API_KEY|| '';
    this.secretKey = config.secretKey ||process.env.GATE_SECRET_KEY|| '';
  }

  _createSpotApi() {
    const GateApi = require('gate-api');
    const config = new GateApi.ApiClient();
    config.setApiKeySecret(this.apiKey, this.secretKey);
    return new GateApi.SpotApi(config);
  }

  _createWalletApi() {
    const GateApi = require('gate-api');
    const config = new GateApi.ApiClient();
    config.setApiKeySecret(this.apiKey, this.secretKey);
    return new GateApi.WalletApi(config);
  }

  _createFuturesApi() {
    const GateApi = require('gate-api');
    const config = new GateApi.ApiClient();
    config.setApiKeySecret(this.apiKey, this.secretKey);
    return new GateApi.FuturesApi(config);
  }

  _createPerpetualApi() {
    const GateApi = require('gate-api');
    const config = new GateApi.ApiClient();
    config.setApiKeySecret(this.apiKey, this.secretKey);
    return new GateApi.FuturesApi(config);
  }

  _checkAuth() {
    if (!this.apiKey || !this.secretKey) {
      throw new Error('请先配置 API 密钥');
    }
  }

  install(framework) {
    super.install(framework);
    const { z } = require('zod');

    // 1. 配置 API 密钥
    this.registerTool('gate_configure_api', {
      description: '配置 Gate.io API 密钥（安全存储）',
      inputSchema: z.object({
        api_key: z.string().describe('Gate.io API Key'),
        secret: z.string().describe('Gate.io Secret Key'),
      }),
      execute: async (args) => {
        this.apiKey = args.api_key;
        this.secretKey = args.secret;
        const fs = require('fs');
        fs.writeFileSync(__dirname + '/.env', `GATE_API_KEY=${args.api_key}\nGATE_SECRET_KEY=${args.secret}\n`);
        return { success: true, message: 'Gate API 密钥已成功配置' };
      },
    });

    // 2. 获取 API 配置状态
    this.registerTool('gate_get_api_status', {
      description: '获取 Gate API 配置状态',
      inputSchema: z.object({}),
      execute: async () => {
        const configured = !!(this.apiKey && this.secretKey);
        return { configured, apiKey: configured ? `${this.apiKey.substring(0, 8)}...` : null, hasSecret: !!this.secretKey };
      },
    });

    // 3. 清除 API 配置
    this.registerTool('gate_clear_api_config', {
      description: '清除已存储的 Gate API 配置',
      inputSchema: z.object({}),
      execute: async () => {
        this.apiKey = '';
        this.secretKey = '';
        try { require('fs').unlinkSync(__dirname + '/.env'); } catch (e) {}
        return { success: true, message: 'API 配置已清除' };
      },
    });

    // 4. 测试连接
    this.registerTool('gate_test_connection', {
      description: '测试 Gate.io API 连接和密钥有效性',
      inputSchema: z.object({}),
      execute: async () => {
        try {
          this._checkAuth();
          const spotApi = this._createSpotApi();
          const currencies = await spotApi.listCurrencies();
          return { success: true, message: 'API 连接成功，密钥有效', currencyCount: currencies.body.length };
        } catch (error) { return { success: false, error: error.message }; }
      },
    });

    // 5. 获取市场信息
    this.registerTool('gate_get_market_info', {
      description: '获取 Gate.io 市场信息',
      inputSchema: z.object({
        currency_pair: z.string().describe('交易对，如 BTC_USDT'),
        info_type: z.enum(['book', 'trades', 'tickers']).optional().describe('信息类型'),
      }),
      execute: async (args) => {
        try {
          this._checkAuth();
          const spotApi = this._createSpotApi();
          const { currency_pair, info_type } = args;
          if (info_type === 'book' || !info_type) {
            const book = await spotApi.listOrderBook(currency_pair, { limit: 10 });
            return { success: true, type: 'order_book', currency_pair, bids: book.body.bids, asks: book.body.asks };
          } else if (info_type === 'tickers') {
            const tickers = await spotApi.listTickers(currency_pair);
            const t = tickers.body.find(x => x.currencyPair === currency_pair) || tickers.body[0];
            return {
              success: true, type: 'ticker', currency_pair: t.currencyPair,
              last: t.last, high_24h: t.high24h, low_24h: t.low24h,
              volume_24h: t.baseVolume, quote_volume_24h: t.quoteVolume, change_percentage_24h: t.changePercentage,
            };
          } else if (info_type === 'trades') {
            const trades = await spotApi.listTrades(currency_pair);
            return { success: true, type: 'trades', currency_pair, trades: trades.body.slice(0, 20) };
          }
          return { success: false, error: '未知的信息类型' };
        } catch (error) { return { success: false, error: error.message }; }
      },
    });

    // 6. 获取账户余额
    this.registerTool('gate_get_account_balance', {
      description: '获取 Gate.io 账户余额信息',
      inputSchema: z.object({ currency: z.string().optional() }),
      execute: async (args) => {
        try {
          this._checkAuth();
          const spotApi = this._createSpotApi();
          const account = await spotApi.listSpotAccounts();
          let balances = account.body;
          if (args.currency) {
            balances = balances.filter(a => a.currency.toLowerCase() === args.currency.toLowerCase());
          }
          const nonZero = balances.filter(b => parseFloat(b.available) > 0 || parseFloat(b.locked) > 0);
          return {
            success: true,
            balances: nonZero.map(b => ({
              currency: b.currency, available: b.available, locked: b.locked,
              total: parseFloat(b.available) + parseFloat(b.locked),
            })),
          };
        } catch (error) { return { success: false, error: error.message }; }
      },
    });

    // 7. 创建订单
    this.registerTool('gate_create_order', {
      description: '在 Gate.io 创建交易订单',
      inputSchema: z.object({
        currency_pair: z.string(), side: z.enum(['buy', 'sell']),
        order_type: z.enum(['limit', 'market']), amount: z.string(), price: z.string(), text: z.string().optional(),
      }),
      execute: async (args) => {
        try {
          this._checkAuth();
          const spotApi = this._createSpotApi();
          const order = {
            text: args.text || `order_${Date.now()}`, currency_pair: args.currency_pair,
            type: args.order_type, side: args.side, amount: args.amount,
          };
          if (args.order_type === 'limit' && args.price) order.price = args.price;
          const result = await spotApi.createOrder(order);
          const r = result.body;
          return {
            success: true, order_id: r.id, currency_pair: r.currency_pair,
            type: r.type, side: r.side, amount: r.amount,
            price: r.price, status: r.status, create_time: r.create_time,
          };
        } catch (error) { return { success: false, error: error.message }; }
      },
    });

    // 8. 取消订单
    this.registerTool('gate_cancel_order', {
      description: '取消 Gate.io 上的指定订单',
      inputSchema: z.object({ currency_pair: z.string(), order_id: z.string() }),
      execute: async (args) => {
        try {
          this._checkAuth();
          const spotApi = this._createSpotApi();
          const result = await spotApi.cancelOrder(args.order_id, args.currency_pair);
          return { success: true, order_id: result.body.id, status: result.body.status, message: '订单已取消' };
        } catch (error) { return { success: false, error: error.message }; }
      },
    });

    // 9. 获取订单信息
    this.registerTool('gate_get_order_info', {
      description: '获取 Gate.io 指定订单的详细信息',
      inputSchema: z.object({ currency_pair: z.string(), order_id: z.string() }),
      execute: async (args) => {
        try {
          this._checkAuth();
          const spotApi = this._createSpotApi();
          const order = await spotApi.getOrder(args.order_id, args.currency_pair);
          const o = order.body;
          return {
            success: true, order_id: o.id, currency_pair: o.currency_pair,
            type: o.type, side: o.side, amount: o.amount, price: o.price,
            filled_amount: o.filled_amount, status: o.status,
            create_time: o.create_time, update_time: o.update_time,
          };
        } catch (error) { return { success: false, error: error.message }; }
      },
    });

    // 10. 获取未完成订单
    this.registerTool('gate_get_open_orders', {
      description: '获取 Gate.io 当前所有未完成的订单',
      inputSchema: z.object({ currency_pair: z.string().optional(), limit: z.number().optional() }),
      execute: async (args) => {
        try {
          this._checkAuth();
          const spotApi = this._createSpotApi();
          const result = await spotApi.listAllOpenOrders({ currency_pair: args.currency_pair, limit: args.limit || 100 });
          const orders = (Array.isArray(result.body) ? result.body : []).map(order => ({
            order_id: order.id, currency_pair: order.currency_pair, type: order.type,
            side: order.side, amount: order.amount, price: order.price,
            filled_amount: order.filled_amount, status: order.status, create_time: order.create_time,
          }));
          return { success: true, count: orders.length, orders };
        } catch (error) { return { success: false, error: error.message }; }
      },
    });

    // 11. 获取 K 线数据
    this.registerTool('gate_get_ohlcv_data', {
      description: '获取 Gate.io K线/烛线数据',
      inputSchema: z.object({
        currency_pair: z.string(), timeframe: z.enum(['10s', '1m', '5m', '15m', '30m', '1h', '4h', '8h', '1d', '7d', '30d']), limit: z.number().optional(),
      }),
      execute: async (args) => {
        try {
          this._checkAuth();
          const spotApi = this._createSpotApi();
          const klines = await spotApi.listCandlesticks(args.currency_pair, { interval: args.timeframe, limit: args.limit || 100 });
          return {
            success: true, currency_pair: args.currency_pair, timeframe: args.timeframe,
            count: klines.body.length,
            klines: klines.body.reverse().map(k => ({
              timestamp: k[0], volume: k[1], open: k[2], high: k[3], low: k[4], close: k[5],
            })),
          };
        } catch (error) { return { success: false, error: error.message }; }
      },
    });

    // 12. 获取交易对列表
    this.registerTool('gate_get_trading_pairs', {
      description: '获取 Gate.io 支持的所有现货交易对',
      inputSchema: z.object({ quote: z.string().optional() }),
      execute: async (args) => {
        try {
          this._checkAuth();
          const spotApi = this._createSpotApi();
          const allPairs = await spotApi.listCurrencyPairs();
          let pairs = allPairs.body;
          if (args.quote) pairs = pairs.filter(p => p.quote.toLowerCase() === args.quote.toLowerCase());
          return {
            success: true, count: pairs.length,
            pairs: pairs.map(p => ({ id: p.id, base: p.base, quote: p.quote })),
          };
        } catch (error) { return { success: false, error: error.message }; }
      },
    });

    // 13. 批量取消订单
    this.registerTool('gate_cancel_all_orders', {
      description: '批量取消 Gate.io 上的订单',
      inputSchema: z.object({ currency_pair: z.string().optional() }),
      execute: async (args) => {
        try {
          this._checkAuth();
          const spotApi = this._createSpotApi();
          const result = await spotApi.cancelOrders([], args.currency_pair);
          return { success: true, cancelled_count: result.body.length, message: `已取消 ${result.body.length} 个订单` };
        } catch (error) { return { success: false, error: error.message }; }
      },
    });

    // 14. 获取充值地址
    this.registerTool('gate_get_deposit_address', {
      description: '获取 Gate.io 充值地址',
      inputSchema: z.object({ currency: z.string(), network: z.string().optional() }),
      execute: async (args) => {
        try {
          this._checkAuth();
          const walletApi = this._createWalletApi();
          const result = await walletApi.generateDepositAddress(args.currency, args.network);
          return {
            success: true, currency: args.currency,
            address: result.body.deposit_addresses?.[0]?.address || result.body.address,
            memo: result.body.deposit_addresses?.[0]?.address_hint,
          };
        } catch (error) { return { success: false, error: error.message }; }
      },
    });

    // 15. 获取提现记录
    this.registerTool('gate_get_withdrawals', {
      description: '获取 Gate.io 提现记录',
      inputSchema: z.object({ currency: z.string().optional(), limit: z.number().optional() }),
      execute: async (args) => {
        try {
          this._checkAuth();
          const walletApi = this._createWalletApi();
          const result = await walletApi.withdrawals(args.currency, { limit: args.limit || 100 });
          return {
            success: true, count: result.body.length,
            withdrawals: result.body.map(w => ({ id: w.id, currency: w.currency, amount: w.amount, address: w.address, status: w.status, create_time: w.create_time })),
          };
        } catch (error) { return { success: false, error: error.message }; }
      },
    });

    // 16. 获取充值记录
    this.registerTool('gate_get_deposits', {
      description: '获取 Gate.io 充值记录',
      inputSchema: z.object({ currency: z.string().optional(), limit: z.number().optional() }),
      execute: async (args) => {
        try {
          this._checkAuth();
          const walletApi = this._createWalletApi();
          const result = await walletApi.deposits(args.currency, { limit: args.limit || 100 });
          return {
            success: true, count: result.body.length,
            deposits: result.body.map(d => ({ id: d.id, currency: d.currency, amount: d.amount, address: d.address, status: d.status, create_time: d.create_time })),
          };
        } catch (error) { return { success: false, error: error.message }; }
      },
    });

    // ========== 合约交易功能 (Futures API) ==========

    // 17. 获取合约账户余额
    this.registerTool('gate_get_perpetual_balance', {
      description: '获取 Gate.io 合约账户余额',
      inputSchema: z.object({ settle: z.string().optional().describe('结算货币，如 USDT') }),
      execute: async (args) => {
        try {
          this._checkAuth();
          const futuresApi = this._createFuturesApi();
          const settle = (args.settle || 'USDT').toLowerCase();
          const result = await futuresApi.listFuturesAccounts(settle);
          const a = Array.isArray(result.body) ? result.body[0] : result.body;
          return {
            success: true,
            settle,
            order_book: a.order_book || 0,
            available: a.available || 0,
            order_margin: a.order_margin || 0,
            position_margin: a.position_margin || 0,
            equity: a.equity || 0,
            total_size: a.total_size || 0,
          };
        } catch (error) { return { success: false, error: error.message }; }
      },
    });

    // 18. 获取合约持仓
    this.registerTool('gate_get_perpetual_positions', {
      description: '获取 Gate.io 合约持仓信息',
      inputSchema: z.object({
        settle: z.string().optional().describe('结算货币，如 USDT'),
        contract: z.string().optional().describe('合约名称，如 BTC_USD'),
      }),
      execute: async (args) => {
        try {
          this._checkAuth();
          const futuresApi = this._createFuturesApi();
          const settle = (args.settle || 'USDT').toLowerCase();
          const result = await futuresApi.listPositions(settle);
          let positions = Array.isArray(result.body) ? result.body : [];
          if (args.contract) {
            positions = positions.filter(p => p.contract === args.contract);
          }
          return {
            success: true,
            settle,
            count: positions.length,
            positions: positions.map(p => ({
              contract: p.contract, size: p.size, entry_price: p.entry_price,
              margin: p.margin, leverage: p.leverage, unrealised_pnl: p.unrealised_pnl,
              realised_pnl: p.realised_pnl, mode: p.mode,
            })),
          };
        } catch (error) { return { success: false, error: error.message }; }
      },
    });

    // 19. 创建合约订单
    this.registerTool('gate_create_perpetual_order', {
      description: '在 Gate.io 创建合约订单',
      inputSchema: z.object({
        settle: z.string().describe('结算货币，如 USDT'),
        contract: z.string().describe('合约名称，如 BTC_USD'),
        side: z.enum(['buy', 'sell']).describe('买入或卖出'),
        size: z.string().describe('数量（正数为开多，负数为开空）'),
        price: z.string().optional().describe('价格（市价单可不填）'),
        order_type: z.enum(['limit', 'market', 'post_only']).optional().describe('订单类型'),
        reduce_only: z.boolean().optional().describe('是否只减仓'),
      }),
      execute: async (args) => {
        try {
          this._checkAuth();
          const futuresApi = this._createFuturesApi();
          const settle = args.settle.toLowerCase();
          
          // 构造订单对象 - settle 不能在订单内部
          const order = {
            contract: args.contract,
            size: args.size,
            side: args.side,
            type: args.order_type || 'market',
          };
          if (args.price) order.price = args.price;
          if (args.reduce_only !== undefined) order.reduce_only = args.reduce_only;
          
          // SDK签名: createFuturesOrder(settle, futuresOrder, opts)
          const result = await futuresApi.createFuturesOrder(settle, order);
          const r = result.body;
          return {
            success: true,
            id: String(r.id),
            contract: r.contract,
            side: r.side,
            size: r.size,
            price: r.price,
            order_type: r.type,
            status: r.status,
            fill_price: r.fill_price,
            create_time: r.create_time,
          };
        } catch (error) { 
          return { success: false, error: error.message }; }
      },
    });

    // 20. 取消合约订单
    this.registerTool('gate_cancel_perpetual_order', {
      description: '取消 Gate.io 合约订单',
      inputSchema: z.object({
        settle: z.string().describe('结算货币，如 USDT'),
        contract: z.string().describe('合约名称'),
        order_id: z.string().describe('订单ID'),
      }),
      execute: async (args) => {
        try {
          this._checkAuth();
          const futuresApi = this._createFuturesApi();
          const result = await futuresApi.cancelFuturesOrder(args.order_id, args.contract, args.settle);
          return {
            success: true,
            id: String(result.body.id),
            contract: result.body.contract,
            status: result.body.status,
            message: '合约订单已取消',
          };
        } catch (error) { return { success: false, error: error.message }; }
      },
    });

    // 21. 获取合约订单信息
    this.registerTool('gate_get_perpetual_order_info', {
      description: '获取 Gate.io 合约订单详细信息',
      inputSchema: z.object({
        settle: z.string().describe('结算货币，如 USDT'),
        contract: z.string().describe('合约名称'),
        order_id: z.string().describe('订单ID'),
      }),
      execute: async (args) => {
        try {
          this._checkAuth();
          const futuresApi = this._createFuturesApi();
          const result = await futuresApi.getFuturesOrder(args.order_id, args.contract, args.settle);
          const o = result.body;
          return {
            success: true,
            id: String(o.id),
            contract: o.contract,
            side: o.side,
            size: o.size,
            price: o.price,
            order_type: o.order_type,
            filled_amount: o.filled_amount,
            filled_size: o.filled_size,
            status: o.status,
            create_time: o.create_time,
            update_time: o.update_time,
          };
        } catch (error) { return { success: false, error: error.message }; }
      },
    });

    // 22. 获取合约未完成订单
    this.registerTool('gate_get_perpetual_open_orders', {
      description: '获取 Gate.io 合约未完成订单',
      inputSchema: z.object({
        settle: z.string().optional().describe('结算货币，如 USDT'),
        contract: z.string().optional().describe('合约名称'),
      }),
      execute: async (args) => {
        try {
          this._checkAuth();
          const futuresApi = this._createFuturesApi();
          const settle = (args.settle || 'USDT').toLowerCase();
          
          // SDK签名: listFuturesOrders(settle, status, opts)
          // status: open = 未完成, finished = 已完成
          const status = 'open';
          const opts = {};
          if (args.contract) opts.contract = args.contract;
          
          const result = await futuresApi.listFuturesOrders(settle, status, opts);
          const orders = (Array.isArray(result.body) ? result.body : []);
          return {
            success: true,
            settle,
            count: orders.length,
            orders: orders.map(o => ({
              id: String(o.id),
              contract: o.contract,
              side: o.side,
              size: o.size,
              price: o.price,
              order_type: o.type,
              filled_size: o.filled_size,
              status: o.status,
              create_time: o.create_time,
            })),
          };
        } catch (error) { return { success: false, error: error.message }; }
      },
    });

    // 23. 获取合约市场数据
    this.registerTool('gate_get_perpetual_market', {
      description: '获取 Gate.io 合约市场信息',
      inputSchema: z.object({
        settle: z.string().optional().describe('结算货币，如 USDT'),
        contract: z.string().optional().describe('合约名称'),
        info_type: z.enum(['book', 'trades', 'tickers']).optional().describe('信息类型'),
      }),
      execute: async (args) => {
        try {
          this._checkAuth();
          const futuresApi = this._createFuturesApi();
          const settle = (args.settle || 'USDT').toLowerCase();
          const { info_type, contract } = args;
          
          if (info_type === 'book' || !info_type) {
            // SDK签名: listFuturesOrderBook(settle, contract, opts)
            const book = await futuresApi.listFuturesOrderBook(settle, contract || 'BTC_USDT');
            return {
              success: true,
              type: 'order_book',
              contract: contract || 'BTC_USDT',
              settle,
              bids: book.body.bids?.slice(0, 10) || [],
              asks: book.body.asks?.slice(0, 10) || [],
            };
          } else if (info_type === 'tickers') {
            const tickers = await futuresApi.listFuturesTickers(settle);
            let t = Array.isArray(tickers.body) ? tickers.body : [];
            if (contract) t = t.filter(x => x.contract === contract);
            return {
              success: true,
              type: 'tickers',
              settle,
              tickers: t.slice(0, 20).map(x => ({
                contract: x.contract,
                last: x.last,
                mark_price: x.mark_price,
                index_price: x.index_price,
                funding_rate: x.funding_rate,
                volume_24h: x.volume_24h,
                change_24h: x.change_24h,
              })),
            };
          } else if (info_type === 'trades') {
            // SDK签名: listFuturesTrades(contract, settle, opts)
            const trades = await futuresApi.listFuturesTrades(contract || 'BTC_USDT', settle);
            return {
              success: true,
              type: 'trades',
              contract: contract || 'BTC_USDT',
              settle,
              trades: (trades.body || []).slice(0, 20),
            };
          }
          return { success: false, error: '未知的信息类型' };
        } catch (error) { return { success: false, error: error.message }; }
      },
    });

    // 24. 获取合约K线数据
    this.registerTool('gate_get_perpetual_ohlcv', {
      description: '获取 Gate.io 合约K线数据',
      inputSchema: z.object({
        settle: z.string().optional().describe('结算货币，如 USDT'),
        contract: z.string().describe('合约名称，如 BTC_USD'),
        timeframe: z.enum(['10s', '1m', '5m', '15m', '30m', '1h', '4h', '8h', '1d', '7d', '30d']).optional().describe('时间周期'),
        limit: z.number().optional().describe('返回条数'),
      }),
      execute: async (args) => {
        try {
          this._checkAuth();
          const futuresApi = this._createFuturesApi();
          const settle = (args.settle || 'USDT').toLowerCase();
          // SDK签名: listFuturesCandlesticks(settle, contract, opts)
          const klines = await futuresApi.listFuturesCandlesticks(
            settle,
            args.contract,
            { interval: args.timeframe || '1h', limit: args.limit || 100 }
          );
          return {
            success: true,
            contract: args.contract,
            settle,
            timeframe: args.timeframe || '1h',
            count: (klines.body || []).length,
            klines: (klines.body || []).reverse().map(k => ({
              timestamp: k.t,
              volume: k.v,
              open: k.o,
              high: k.h,
              low: k.l,
              close: k.c,
            })),
          };
        } catch (error) { return { success: false, error: error.message }; }
      },
    });

    // 25. 获取合约列表
    this.registerTool('gate_get_perpetual_contracts', {
      description: '获取 Gate.io 支持的合约列表',
      inputSchema: z.object({ settle: z.string().optional().describe('结算货币，如 USDT') }),
      execute: async (args) => {
        try {
          this._checkAuth();
          const futuresApi = this._createFuturesApi();
          const settle = (args.settle || 'USDT').toLowerCase();
          const result = await futuresApi.listFuturesContracts(settle);
          return {
            success: true,
            settle,
            count: (result.body || []).length,
            contracts: (result.body || []).slice(0, 50).map(c => ({
              name: c.name,
              base: c.base_currency,
              quote: c.quote_currency,
              quanto_multiplier: c.quanto_multiplier,
              is_inverse: c.is_inverse,
              order_price_round: c.order_price_round,
              funding_rate: c.funding_rate,
              leverage_min: c.leverage_min,
              leverage_max: c.leverage_max,
            })),
          };
        } catch (error) { return { success: false, error: error.message }; }
      },
    });

    // 26. 取消所有合约订单
    this.registerTool('gate_cancel_all_perpetual_orders', {
      description: '取消 Gate.io 合约所有未完成订单',
      inputSchema: z.object({
        settle: z.string().describe('结算货币，如 USDT'),
        contract: z.string().optional().describe('合约名称（可选）'),
      }),
      execute: async (args) => {
        try {
          this._checkAuth();
          const futuresApi = this._createFuturesApi();
          const result = await futuresApi.cancelFuturesOrders(args.contract, args.settle);
          return {
            success: true,
            cancelled_count: (result.body || []).length,
            message: `已取消 ${(result.body || []).length} 个合约订单`,
          };
        } catch (error) { return { success: false, error: error.message }; }
      },
    });

    // 27. 设置合约杠杆
    this.registerTool('gate_set_perpetual_leverage', {
      description: '设置 Gate.io 合约杠杆倍数',
      inputSchema: z.object({
        settle: z.string().describe('结算货币，如 USDT'),
        contract: z.string().describe('合约名称'),
        leverage: z.number().describe('杠杆倍数'),
        mode: z.enum(['cross', 'isolated']).optional().describe('仓位模式'),
      }),
      execute: async (args) => {
        try {
          this._checkAuth();
          const futuresApi = this._createFuturesApi();
          // 先获取当前模式
          try {
            const modeResult = await futuresApi.updatePositionCrossMode(args.contract, args.settle, {
              cross_leverage_limit: args.leverage,
            });
            return {
              success: true,
              contract: args.contract,
              leverage: args.leverage,
              mode: modeResult.body,
              message: '杠杆设置成功',
            };
          } catch (e) {
            // 如果 cross mode 失败，尝试 dual mode
            const result = await futuresApi.setPositionMode(args.settle, {
              mode: args.mode || 'both',
            });
            return {
              success: true,
              contract: args.contract,
              leverage: args.leverage,
              message: '杠杆设置成功',
            };
          }
        } catch (error) { return { success: false, error: error.message }; }
      },
    });

  }
};
module.exports ={ GateTradingPlugin };
