import { TradingService, ServiceStatus } from '../types.js'
import { AccountManager } from '../account/AccountManager.js'
import { logger } from '../../utils/logger.js'

/**
 * 订单清理服务 - 负责清理历史未成交订单
 */
export class OrderCleanupService implements TradingService {
  private isRunning = false
  private cleanupInterval: NodeJS.Timeout | null = null
  private cleanupInProgress = false

  constructor(
    private accountManager: AccountManager,
    private cleanupIntervalMs: number = 300000, // 默认5分钟清理一次
    private maxOrderAge: number = 600000, // 默认10分钟的订单被认为是历史订单
    private maxOrderCount: number = 10, // 最大允许的未成交订单数量
  ) {}

  async initialize(): Promise<void> {
    logger.info('OrderCleanupService 初始化')
  }

  async start(): Promise<void> {
    if (this.isRunning) {
      logger.warn('OrderCleanupService 已在运行')
      return
    }

    this.isRunning = true
    logger.info('OrderCleanupService 启动')

    // 启动时立即执行一次清理
    this.performCleanup().catch(error => {
      logger.error('初始订单清理失败', { error: error.message })
    })

    // 设置定期清理
    this.cleanupInterval = setInterval(() => {
      if (!this.cleanupInProgress) {
        this.performCleanup().catch(error => {
          logger.error('定期订单清理失败', { error: error.message })
        })
      }
    }, this.cleanupIntervalMs)

    logger.info(`✅ 订单清理服务已启动，每${this.cleanupIntervalMs/1000}秒清理一次`)
  }

  async stop(): Promise<void> {
    if (!this.isRunning) return

    this.isRunning = false

    if (this.cleanupInterval) {
      clearInterval(this.cleanupInterval)
      this.cleanupInterval = null
    }

    // 等待当前清理完成
    while (this.cleanupInProgress) {
      await new Promise(resolve => setTimeout(resolve, 100))
    }

    logger.info('OrderCleanupService 已停止')
  }

  getStatus(): ServiceStatus {
    return {
      name: 'OrderCleanupService',
      status: this.isRunning ? 'running' : 'stopped',
      lastUpdate: Date.now(),
      details: {
        cleanupInProgress: this.cleanupInProgress,
        cleanupInterval: `${this.cleanupIntervalMs/1000}s`,
        maxOrderAge: `${this.maxOrderAge/1000}s`,
        maxOrderCount: this.maxOrderCount,
        strategy: 'intelligent', // 智能清理策略
      },
    }
  }

  /**
   * 执行订单清理
   */
  private async performCleanup(): Promise<void> {
    if (this.cleanupInProgress) {
      logger.debug('订单清理正在进行中，跳过本次执行')
      return
    }

    this.cleanupInProgress = true
    logger.info('🧹 开始执行订单清理...')

    try {
      const accounts = this.accountManager.getAccounts()
      let totalCleaned = 0
      let totalSkipped = 0
      let totalErrors = 0

      // 遍历账户，使用正确的客户端ID格式 (pacifica-1, pacifica-2, etc.)
      for (let i = 0; i < accounts.length; i++) {
        const clientId = `pacifica-${i + 1}`
        try {
          const result = await this.cleanupAccountOrders(clientId)
          totalCleaned += result.cleaned
          totalSkipped += result.skipped
          totalErrors += result.errors
        } catch (error: any) {
          logger.error(`清理账户 ${clientId} 订单失败`, { error: error.message })
          totalErrors++
        }
      }

      logger.info(`✅ 订单清理完成: 清理${totalCleaned}个, 跳过${totalSkipped}个, 错误${totalErrors}个`)
    } catch (error: any) {
      logger.error('执行订单清理时出错', { error: error.message })
    } finally {
      this.cleanupInProgress = false
    }
  }

  /**
   * 清理单个账户的订单
   */
  private async cleanupAccountOrders(accountId: string): Promise<{
    cleaned: number
    skipped: number
    errors: number
  }> {
    logger.debug(`检查账户 ${accountId} 的历史订单`)

    const client = this.accountManager.getClient(accountId)
    if (!client) {
      logger.warn(`找不到账户 ${accountId} 的客户端`)
      return { cleaned: 0, skipped: 0, errors: 1 }
    }

    // 获取账户信息用于订单取消
    const accounts = this.accountManager.getAccounts()
    const accountIndex = parseInt(accountId.replace('pacifica-', '')) - 1
    const accountDetails = accounts[accountIndex]

    if (!accountDetails) {
      logger.error(`无法找到账户 ${accountId} 的详细信息`)
      return { cleaned: 0, skipped: 0, errors: 1 }
    }

    let cleaned = 0
    let skipped = 0
    let errors = 0

    try {
      // 查询所有开放订单
      const response = await client.getOpenOrders()

      // 处理不同的响应格式 - 根据实际API调试结果
      let openOrders = []
      if (response && response.success && Array.isArray(response.data)) {
        // Pacifica API实际返回格式: {success: true, data: [orders...]}
        openOrders = response.data
      } else if (Array.isArray(response)) {
        // 直接数组格式 (根据文档格式)
        openOrders = response
      } else if (response && response.data && Array.isArray(response.data)) {
        // 通用包装格式: {data: [orders...]}
        openOrders = response.data
      } else if (response && Array.isArray(response.orders)) {
        // 其他可能的格式: {orders: [orders...]}
        openOrders = response.orders
      } else {
        logger.error(`账户 ${accountId} 返回了意外的订单数据格式`, {
          responseType: typeof response,
          hasSuccess: response?.success,
          hasData: !!response?.data,
          isDataArray: Array.isArray(response?.data),
          hasOrders: !!response?.orders,
          responseStructure: response && typeof response === 'object' ? Object.keys(response) : 'not object'
        })
        return { cleaned: 0, skipped: 0, errors: 1 }
      }

      logger.debug(`账户 ${accountId} 查询到 ${openOrders.length} 个未成交订单`)

      if (openOrders.length === 0) {
        return { cleaned, skipped, errors }
      }

      // 调试：输出第一个订单的结构
      if (openOrders.length > 0) {
        logger.debug(`订单结构示例:`, {
          sampleOrder: JSON.stringify(openOrders[0]),
          keys: Object.keys(openOrders[0])
        })
      }

      const now = Date.now()

      // 处理订单并按时间排序（最老的在前）
      const processedOrders = []
      for (const order of openOrders) {
        // Pacifica API实际返回格式: 直接的订单对象
        // 字段名: order_id, created_at (毫秒时间戳)
        const orderId = order?.order_id || order?.client_order_id
        const orderTimestamp = order?.created_at || order?.updated_at

        // 如果无法获取订单ID或时间，记录详细信息并跳过
        if (!orderId || !orderTimestamp) {
          logger.warn('跳过无效订单（缺少ID或时间）', {
            orderId,
            orderTimestamp,
            order_id: order?.order_id,
            client_order_id: order?.client_order_id,
            created_at: order?.created_at,
            updated_at: order?.updated_at,
            orderKeys: Object.keys(order || {}),
            orderSample: JSON.stringify(order).substring(0, 200)
          })
          errors++
          continue
        }

        // 时间戳已经是毫秒格式，直接使用
        const orderTime = typeof orderTimestamp === 'number' ? orderTimestamp : parseInt(orderTimestamp)

        processedOrders.push({
          orderId,
          orderTime,
          orderAge: now - orderTime,
          originalOrder: order
        })
      }

      // 按时间排序：最老的订单在前
      processedOrders.sort((a, b) => a.orderTime - b.orderTime)

      logger.info(`账户 ${accountId} 发现 ${processedOrders.length} 个订单，最大允许数量: ${this.maxOrderCount}`)

      // 智能清理逻辑
      let ordersToCancel = []

      // 1. 首先检查是否超过最大订单数量限制
      if (processedOrders.length > this.maxOrderCount) {
        const excessCount = processedOrders.length - this.maxOrderCount
        ordersToCancel = processedOrders.slice(0, excessCount) // 取最老的订单
        logger.info(`⚠️ 订单数量超限 (${processedOrders.length}>${this.maxOrderCount})，需要清理 ${excessCount} 个最老订单`)
      }

      // 2. 检查超时的历史订单（在剩余的订单中）
      const remainingOrders = processedOrders.slice(ordersToCancel.length)
      const expiredOrders = remainingOrders.filter(order => order.orderAge > this.maxOrderAge)
      ordersToCancel = ordersToCancel.concat(expiredOrders)

      if (expiredOrders.length > 0) {
        logger.info(`⏰ 发现 ${expiredOrders.length} 个超时订单 (>${this.maxOrderAge/1000}s)`)
      }

      // 3. 执行订单取消 - 使用正确的 CancelOrderPayload 格式
      for (const orderInfo of ordersToCancel) {
        try {
          logger.info(`🗑️ 清理订单: ${orderInfo.orderId} (年龄: ${Math.round(orderInfo.orderAge/1000)}s)`)

          // 构造符合API要求的取消订单载荷
          const cancelPayload = {
            account: accountDetails.account || accountDetails.publicKey,
            symbol: orderInfo.originalOrder.symbol || 'BTC', // 默认BTC符号，实际应从订单获取
            orderId: orderInfo.orderId,
            expiryWindow: 30000 // 30秒过期时间
          }

          // 调用正确的cancelOrder方法，传入完整的payload
          await client.cancelOrder(cancelPayload)
          cleaned++

          // 添加延迟避免API限制
          await new Promise(resolve => setTimeout(resolve, 200))
        } catch (cancelError: any) {
          logger.warn(`取消订单失败: ${orderInfo.orderId}`, {
            error: cancelError.message,
            account: accountDetails.account?.substring(0, 8) + '...',
            symbol: orderInfo.originalOrder.symbol
          })
          errors++
        }
      }

      // 4. 统计跳过的订单
      skipped = processedOrders.length - ordersToCancel.length

      logger.info(`账户 ${accountId} 清理完成: 清理${cleaned}个, 跳过${skipped}个, 错误${errors}个`)
    } catch (error: any) {
      logger.error(`查询账户 ${accountId} 订单失败`, { error: error.message })
      errors++
    }

    return { cleaned, skipped, errors }
  }

  /**
   * 手动触发清理
   */
  async manualCleanup(): Promise<void> {
    if (!this.isRunning) {
      throw new Error('OrderCleanupService 未运行')
    }

    logger.info('🔧 手动触发订单清理')
    await this.performCleanup()
  }

  /**
   * 获取清理统计
   */
  getCleanupStats() {
    return {
      isRunning: this.isRunning,
      cleanupInProgress: this.cleanupInProgress,
      cleanupInterval: this.cleanupIntervalMs,
      maxOrderAge: this.maxOrderAge,
    }
  }
}