import { EventEmitter } from 'events'
import { PacificaWebSocketClient } from './PacificaWebSocketClient.js'
import { logger } from '../../utils/logger.js'

/**
 * 交易响应接口
 */
interface TradingResponse {
  success: boolean
  data?: any
  error?: string
  orderId?: string
  status?: string
}

/**
 * 市场数据接口
 */
interface MarketData {
  symbol: string
  price: number
  volume: number
  timestamp: number
}

/**
 * 订单簿数据接口
 */
interface OrderBookData {
  symbol: string
  bids: Array<[number, number]>
  asks: Array<[number, number]>
  timestamp: number
}

/**
 * 账户信息接口
 */
interface AccountInfo {
  account: string
  balance: number
  availableBalance: number
  positions: any[]
  marginUsed: number
}

/**
 * Pacifica WebSocket增强适配器
 * 提供完整的API响应处理和市场数据订阅功能
 */
export class PacificaWebSocketAdapter extends EventEmitter {
  private wsClient: PacificaWebSocketClient
  private subscriptions = new Set<string>()
  private marketDataCache = new Map<string, MarketData>()
  private orderBookCache = new Map<string, OrderBookData>()
  private isInitialized = false

  constructor(
    wsUrl: string = 'wss://ws.pacifica.fi/ws', // 使用官方WebSocket端点
    accountId?: string,
    privateKey?: string,
  ) {
    super()
    this.wsClient = new PacificaWebSocketClient(wsUrl, accountId, privateKey)
  }

  /**
   * 初始化WebSocket连接
   */
  async initialize(): Promise<void> {
    try {
      await this.wsClient.connect()
      this.setupEventHandlers()
      this.isInitialized = true
      logger.info('PacificaWebSocketAdapter初始化成功')
    } catch (error: any) {
      logger.error('PacificaWebSocketAdapter初始化失败', { error: error.message })
      throw error
    }
  }

  /**
   * 设置事件处理器
   */
  private setupEventHandlers(): void {
    // 监听价格数据流
    this.wsClient.on('prices', (data: any) => {
      this.handlePricesUpdate(data)
    })

    // 监听订单簿数据流
    this.wsClient.on('orderbook', (data: any) => {
      this.handleOrderBookUpdate(data)
    })

    // 监听账户余额数据流
    this.wsClient.on('balance', (data: any) => {
      this.emit('balance', data)
    })

    // 监听仓位数据流
    this.wsClient.on('positions', (data: any) => {
      this.emit('positions', data)
    })

    // 监听订单更新数据流
    this.wsClient.on('orders', (data: any) => {
      this.emit('orders', data)
    })
  }

  /**
   * 处理价格更新
   */
  private handlePricesUpdate(data: any): void {
    // 根据Pacifica价格数据格式处理
    if (typeof data === 'object') {
      Object.entries(data).forEach(([symbol, priceInfo]: [string, any]) => {
        const marketData: MarketData = {
          symbol,
          price: parseFloat(priceInfo.price || '0'),
          volume: parseFloat(priceInfo.volume_24h || '0'),
          timestamp: Date.now(),
        }
        this.marketDataCache.set(symbol, marketData)
        this.emit('price', marketData)
      })
    }
  }

  /**
   * 处理订单簿更新
   */
  private handleOrderBookUpdate(data: any): void {
    if (data.symbol) {
      const orderBookData: OrderBookData = {
        symbol: data.symbol,
        bids: data.bids || [],
        asks: data.asks || [],
        timestamp: data.timestamp || Date.now(),
      }
      this.orderBookCache.set(data.symbol, orderBookData)
      this.emit('orderbook', orderBookData)
    }
  }

  /**
   * 获取交易所信息（使用WebSocket请求替换HTTP GET /api/v1/info）
   */
  async getSymbols(): Promise<TradingResponse> {
    if (!this.isInitialized) {
      await this.initialize()
    }

    try {
      const response = await this.wsClient.sendRequest(
        {
          get_info: {},
        },
        15000,
      )

      if (response && response.data) {
        return {
          success: true,
          data: response.data,
        }
      } else {
        return {
          success: false,
          error: `获取交易所信息失败: ${response?.error || 'Unknown error'}`,
        }
      }
    } catch (error: any) {
      logger.error('WebSocket获取交易所信息失败', { error: error.message })
      return {
        success: false,
        error: error.message,
      }
    }
  }

  /**
   * 获取订单簿数据（使用WebSocket请求替换HTTP GET /api/v1/book）
   */
  async getOrderBook(symbol: string): Promise<TradingResponse> {
    if (!this.isInitialized) {
      await this.initialize()
    }

    try {
      const response = await this.wsClient.sendRequest(
        {
          get_orderbook: {
            symbol: symbol,
          },
        },
        10000,
      )

      if (response && response.data) {
        const orderBookData: OrderBookData = {
          symbol,
          bids: response.data.bids || [],
          asks: response.data.asks || [],
          timestamp: Date.now(),
        }

        // 缓存订单簿数据
        this.orderBookCache.set(symbol, orderBookData)
        this.emit('orderbook', orderBookData)

        return {
          success: true,
          data: response.data,
        }
      } else {
        return {
          success: false,
          error: `获取订单簿失败: ${response?.error || 'Unknown error'}`,
        }
      }
    } catch (error: any) {
      logger.error('WebSocket获取订单簿失败', { symbol, error: error.message })
      return {
        success: false,
        error: error.message,
      }
    }
  }

  /**
   * 获取价格数据（使用WebSocket订阅模式替换HTTP GET /api/v1/prices）
   */
  async getPrices(symbols?: string[]): Promise<TradingResponse> {
    if (!this.isInitialized) {
      await this.initialize()
    }

    try {
      // 启动价格订阅，数据将通过事件流实时推送
      await this.wsClient.subscribePrices(symbols)

      return {
        success: true,
        data: { message: '价格数据订阅已启动，数据将通过实时事件推送' },
      }
    } catch (error: any) {
      logger.error('WebSocket订阅价格数据失败', { symbols, error: error.message })
      return {
        success: false,
        error: error.message,
      }
    }
  }

  /**
   * 获取账户余额（使用WebSocket订阅模式替换HTTP GET /api/v1/account/balances）
   */
  async getBalances(account: string): Promise<TradingResponse> {
    if (!this.isInitialized) {
      await this.initialize()
    }

    try {
      // 启动账户余额订阅，数据将通过事件流实时推送
      await this.wsClient.subscribeBalance(account)

      return {
        success: true,
        data: { message: '账户余额订阅已启动，数据将通过实时事件推送' },
      }
    } catch (error: any) {
      logger.error('WebSocket订阅账户余额失败', { account, error: error.message })
      return {
        success: false,
        error: error.message,
      }
    }
  }

  /**
   * 获取账户仓位（使用WebSocket订阅模式替换HTTP GET /api/v1/account/positions）
   */
  async getPositions(account: string): Promise<TradingResponse> {
    if (!this.isInitialized) {
      await this.initialize()
    }

    try {
      // 启动账户仓位订阅，数据将通过事件流实时推送
      await this.wsClient.subscribePositions(account)

      return {
        success: true,
        data: { message: '账户仓位订阅已启动，数据将通过实时事件推送' },
      }
    } catch (error: any) {
      logger.error('WebSocket订阅账户仓位失败', { account, error: error.message })
      return {
        success: false,
        error: error.message,
      }
    }
  }

  /**
   * 下市价单（使用真正的Pacifica WebSocket API）
   */
  async placeMarketOrder(params: {
    symbol: string
    side: 'buy' | 'sell'
    amount: string
    account: string
    signature: string
    reduce_only?: boolean
    slippage_percent?: string
  }): Promise<TradingResponse> {
    if (!this.isInitialized) {
      await this.initialize()
    }

    try {
      const wsParams = {
        account: params.account,
        signature: params.signature,
        timestamp: Date.now(),
        symbol: params.symbol,
        reduce_only: params.reduce_only || false,
        amount: params.amount,
        side: params.side === 'buy' ? 'bid' : ('ask' as 'bid' | 'ask'),
        slippage_percent: params.slippage_percent || '0.5',
        client_order_id: `market-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
      }

      const response = await this.wsClient.createMarketOrder(wsParams)

      if (response && response.data) {
        logger.info('WebSocket市价单下单成功', {
          symbol: params.symbol,
          side: params.side,
          amount: params.amount,
          orderId: response.data.i,
          clientOrderId: response.data.I,
        })

        return {
          success: true,
          data: response.data,
          orderId: response.data.i?.toString(),
          status: 'filled',
        }
      } else {
        logger.warn('WebSocket市价单下单失败', { params, response })

        return {
          success: false,
          error: `下单失败: ${response?.error || 'Unknown error'}`,
        }
      }
    } catch (error: any) {
      logger.error('WebSocket市价单下单异常', { params, error: error.message })
      return {
        success: false,
        error: error.message,
      }
    }
  }

  /**
   * 下限价单（使用真正的Pacifica WebSocket API）
   */
  async placeLimitOrder(params: {
    symbol: string
    side: 'buy' | 'sell'
    amount: string
    price: string
    account: string
    signature: string
    reduce_only?: boolean
  }): Promise<TradingResponse> {
    if (!this.isInitialized) {
      await this.initialize()
    }

    try {
      const wsParams = {
        account: params.account,
        signature: params.signature,
        timestamp: Date.now(),
        symbol: params.symbol,
        reduce_only: params.reduce_only || false,
        amount: params.amount,
        side: params.side === 'buy' ? 'bid' : ('ask' as 'bid' | 'ask'),
        price: params.price,
        client_order_id: `limit-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
      }

      const response = await this.wsClient.createLimitOrder(wsParams)

      if (response && response.data) {
        logger.info('WebSocket限价单下单成功', {
          symbol: params.symbol,
          side: params.side,
          amount: params.amount,
          price: params.price,
          orderId: response.data.i,
          clientOrderId: response.data.I,
        })

        return {
          success: true,
          data: response.data,
          orderId: response.data.i?.toString(),
          status: 'open',
        }
      } else {
        logger.warn('WebSocket限价单下单失败', { params, response })

        return {
          success: false,
          error: `下单失败: ${response?.error || 'Unknown error'}`,
        }
      }
    } catch (error: any) {
      logger.error('WebSocket限价单下单异常', { params, error: error.message })
      return {
        success: false,
        error: error.message,
      }
    }
  }

  /**
   * 取消订单（使用真正的Pacifica WebSocket API）
   */
  async cancelOrder(params: {
    orderId: string
    account: string
    signature: string
    clientOrderId?: string
  }): Promise<TradingResponse> {
    if (!this.isInitialized) {
      await this.initialize()
    }

    try {
      const wsParams = {
        account: params.account,
        signature: params.signature,
        order_id: params.orderId,
        client_order_id: params.clientOrderId,
      }

      const response = await this.wsClient.cancelOrder(wsParams)

      if (response && response.data) {
        logger.info('WebSocket取消订单成功', {
          orderId: params.orderId,
          result: response.data,
        })

        return {
          success: true,
          data: response.data,
        }
      } else {
        logger.warn('WebSocket取消订单失败', { params, response })

        return {
          success: false,
          error: `取消订单失败: ${response?.error || 'Unknown error'}`,
        }
      }
    } catch (error: any) {
      logger.error('WebSocket取消订单异常', { params, error: error.message })
      return {
        success: false,
        error: error.message,
      }
    }
  }

  /**
   * 订阅市场数据
   */
  async subscribeMarketData(symbols: string[]): Promise<void> {
    symbols.forEach(symbol => {
      if (!this.subscriptions.has(symbol)) {
        this.subscriptions.add(symbol)
        logger.debug(`订阅市场数据: ${symbol}`)
      }
    })
  }

  /**
   * 取消订阅市场数据
   */
  async unsubscribeMarketData(symbols: string[]): Promise<void> {
    symbols.forEach(symbol => {
      if (this.subscriptions.has(symbol)) {
        this.subscriptions.delete(symbol)
        logger.debug(`取消订阅市场数据: ${symbol}`)
      }
    })
  }

  /**
   * 获取缓存的市场数据
   */
  getCachedMarketData(symbol: string): MarketData | undefined {
    return this.marketDataCache.get(symbol)
  }

  /**
   * 获取缓存的订单簿数据
   */
  getCachedOrderBook(symbol: string): OrderBookData | undefined {
    return this.orderBookCache.get(symbol)
  }

  /**
   * 获取连接状态
   */
  isConnected(): boolean {
    return this.wsClient.isConnectionOpen()
  }

  /**
   * 获取等待队列长度
   */
  getQueueLength(): number {
    return this.wsClient.getQueueLength()
  }

  /**
   * 关闭连接
   */
  async close(): Promise<void> {
    this.subscriptions.clear()
    this.marketDataCache.clear()
    this.orderBookCache.clear()
    await this.wsClient.close()
    this.isInitialized = false
    logger.info('PacificaWebSocketAdapter已关闭')
  }
}
