/**
 * Pacifica适配器入口
 *
 * 重新导出Pacifica相关的客户端和类型，提供本地化的导入路径
 */

// 重新导出Pacifica客户端
export { PacificaClient } from './PacificaClient'
export { PacificaDataClient } from './PacificaDataClient'
export { PacificaTradingClient } from './PacificaTradingClient'

// 重新导出Pacifica类型
export * from '@/types/pacifica'

import type { PacificaConfig } from '@/types/pacifica'
import { UniversalHttpClient } from '@/utils/universalHttpClient'

import { PacificaClient } from './PacificaClient'

/**
 * 创建Pacifica客户端实例的便捷函数
 */
export function createPacificaClient(
  httpClient: UniversalHttpClient,
  accountId: string,
  config: PacificaConfig,
): PacificaClient {
  return new PacificaClient(httpClient, accountId, config)
}

/**
 * 创建默认配置的Pacifica客户端
 */
export async function createDefaultPacificaClient(
  accountId: string,
  options: {
    baseUrl?: string
    wsUrl?: string
    timeout?: number
    proxyConfig?: any
  } = {},
): Promise<PacificaClient> {
  const { baseUrl = 'https://api.pacifica.fi', wsUrl = 'wss://ws.pacifica.fi', timeout = 10000, proxyConfig } = options

  // 创建HTTP客户端
  const httpClient = new UniversalHttpClient({
    proxyManager: proxyConfig,
    performanceMonitor: { enabled: true },
  })

  // Pacifica配置
  const pacificaConfig: PacificaConfig = {
    baseUrl,
    wsUrl,
    timeout,
  }

  // 创建Pacifica客户端
  return createPacificaClient(httpClient, accountId, pacificaConfig)
}

/**
 * Pacifica快速操作类
 *
 * 提供常用Pacifica操作的快速访问方法
 */
export class PacificaQuickOps {
  private client: PacificaClient

  constructor(client: PacificaClient) {
    this.client = client
  }

  // ============== 快速数据查询 ==============

  /**
   * 快速获取价格
   */
  async getPrice(symbol: string) {
    return this.client.getPrice(symbol)
  }

  /**
   * 快速获取所有价格
   */
  async getAllPrices() {
    return this.client.data.getAllPrices()
  }

  /**
   * 快速获取订单簿
   */
  async getOrderBook(symbol: string, limit = 100) {
    return this.client.getOrderBook(symbol, limit)
  }

  /**
   * 快速获取24小时统计
   */
  async getTicker24hr(symbol?: string) {
    return this.client.getTicker24hr(symbol)
  }

  /**
   * 快速获取K线数据
   */
  async getKlines(symbol: string, interval: string, limit = 500) {
    return this.client.getKlines(symbol, interval, limit)
  }

  /**
   * 快速获取最新交易
   */
  async getRecentTrades(symbol: string, limit = 100) {
    return this.client.data.getRecentTrades(symbol, limit)
  }

  // ============== 快速交易操作 ==============

  /**
   * 快速市价买入
   */
  async marketBuy(symbol: string, quantity?: string, quoteOrderQty?: string) {
    if (quantity) {
      return this.client.marketBuy(symbol, quantity)
    } else if (quoteOrderQty) {
      return this.client.marketBuy(symbol, undefined, quoteOrderQty)
    } else {
      throw new Error('Must specify either quantity or quoteOrderQty')
    }
  }

  /**
   * 快速市价卖出
   */
  async marketSell(symbol: string, quantity: string) {
    return this.client.marketSell(symbol, quantity)
  }

  /**
   * 快速限价买入
   */
  async limitBuy(symbol: string, quantity: string, price: string) {
    return this.client.limitBuy(symbol, quantity, price)
  }

  /**
   * 快速限价卖出
   */
  async limitSell(symbol: string, quantity: string, price: string) {
    return this.client.limitSell(symbol, quantity, price)
  }

  /**
   * 快速取消订单
   */
  async cancelOrder(symbol: string, orderId?: number, origClientOrderId?: string) {
    return this.client.cancelOrder(symbol, orderId, origClientOrderId)
  }

  /**
   * 快速取消所有订单
   */
  async cancelAllOrders(symbol?: string) {
    return this.client.trading.cancelAllOrders(symbol)
  }

  /**
   * 快速获取开放订单
   */
  async getOpenOrders(symbol?: string) {
    return this.client.getOpenOrders(symbol)
  }

  /**
   * 快速获取账户信息
   */
  async getAccount() {
    return this.client.getAccount()
  }

  /**
   * 快速获取余额
   */
  async getBalances() {
    const account = await this.getAccount()
    return account.success ? account.data.balances : []
  }

  /**
   * 快速获取仓位
   * TODO: Implement getPositions method in PacificaTradingClient
   */
  async getPositions() {
    // return this.client.trading.getPositions()
    throw new Error('getPositions method not yet implemented in PacificaTradingClient')
  }

  // ============== 快速WebSocket订阅 ==============

  /**
   * 快速订阅价格流
   */
  async subscribePrices(symbols: string | string[]) {
    const symbolList = Array.isArray(symbols) ? symbols : [symbols]
    for (const symbol of symbolList) {
      await this.client.subscribePriceStream(symbol)
    }
  }

  /**
   * 快速订阅订单簿流
   */
  async subscribeOrderBooks(symbols: string | string[], level = 5) {
    const symbolList = Array.isArray(symbols) ? symbols : [symbols]
    for (const symbol of symbolList) {
      await this.client.subscribeOrderBookStream(symbol, level)
    }
  }

  /**
   * 快速订阅交易流
   */
  async subscribeTrades(symbols: string | string[]) {
    const symbolList = Array.isArray(symbols) ? symbols : [symbols]
    for (const symbol of symbolList) {
      await this.client.subscribeTradeStream(symbol)
    }
  }

  /**
   * 快速订阅用户数据流（订单更新、余额变化等）
   */
  async subscribeUserData() {
    return this.client.subscribeUserDataStream()
  }

  // ============== 事件监听器 ==============

  /**
   * 监听价格更新
   */
  onPriceUpdate(callback: (data: any) => void) {
    this.client.on('ticker', callback)
  }

  /**
   * 监听订单簿更新
   */
  onOrderBookUpdate(callback: (data: any) => void) {
    this.client.on('orderbook', callback)
  }

  /**
   * 监听交易更新
   */
  onTradeUpdate(callback: (data: any) => void) {
    this.client.on('trade', callback)
  }

  /**
   * 监听用户数据更新
   */
  onUserDataUpdate(callback: (data: any) => void) {
    this.client.on('userdata', callback)
  }

  // ============== 工具方法 ==============

  /**
   * 健康检查
   */
  async healthCheck() {
    return this.client.healthCheck()
  }

  /**
   * 获取服务器时间
   */
  async getServerTime() {
    return this.client.getServerTime()
  }

  /**
   * 获取交易所信息
   */
  async getExchangeInfo() {
    return this.client.getExchangeInfo()
  }

  /**
   * 获取连接状态
   */
  getConnectionStatus() {
    return this.client.getConnectionStatus()
  }

  /**
   * 获取客户端配置
   */
  getConfig() {
    return this.client.getConfig()
  }
}

/**
 * 创建Pacifica快速操作实例
 */
export function createPacificaQuickOps(client: PacificaClient): PacificaQuickOps {
  return new PacificaQuickOps(client)
}

/**
 * 一站式Pacifica客户端创建（包含快速操作）
 */
export async function createFullPacificaClient(
  accountId: string,
  options: {
    baseUrl?: string
    wsUrl?: string
    timeout?: number
    proxyConfig?: any
  } = {},
) {
  const client = await createDefaultPacificaClient(accountId, options)
  const quickOps = createPacificaQuickOps(client)

  return {
    client,
    quickOps,
    // 便捷访问
    data: client.data,
    trading: client.trading,
    // 快速方法别名
    price: quickOps.getPrice.bind(quickOps),
    orderbook: quickOps.getOrderBook.bind(quickOps),
    buy: quickOps.marketBuy.bind(quickOps),
    sell: quickOps.marketSell.bind(quickOps),
    limitBuy: quickOps.limitBuy.bind(quickOps),
    limitSell: quickOps.limitSell.bind(quickOps),
    cancel: quickOps.cancelOrder.bind(quickOps),
    account: quickOps.getAccount.bind(quickOps),
    balances: quickOps.getBalances.bind(quickOps),
  }
}
