/**
 * 账户同步服务
 * 基于 contracts/account-sync.md 的规范实现
 * 集成现有的 AccountManager 和类型系统
 */
import { 
  ExchangeAccountManager, 
  AccountSyncRequest, 
  AccountSyncResponse, 
  AccountBalance, 
  AccountPosition,
  AccountUtilization 
} from '../models/ExchangeAccount.js'
import { MonitoringEventManager, MonitoringEvent } from '../models/MonitoringEvent.js'
import { RiskEnvelopeManager } from '../models/RiskEnvelope.js'
import { AccountManager } from '../modules/account/AccountManager.js'
import { AccountState } from '../modules/types.js'
import { logger } from '../utils/logger.js'

export interface ExchangeAdapter {
  getAccountInfo(accountId: string): Promise<{
    balances: AccountBalance[]
    positions: AccountPosition[]
  }>
}

export class AccountSyncService {
  private accountManager: ExchangeAccountManager
  private monitoringManager: MonitoringEventManager
  private riskManager: RiskEnvelopeManager
  private legacyAccountManager: AccountManager // 集成现有的 AccountManager
  private adapters: Map<string, ExchangeAdapter> = new Map()

  constructor(
    accountManager: ExchangeAccountManager,
    monitoringManager: MonitoringEventManager,
    riskManager: RiskEnvelopeManager,
    legacyAccountManager: AccountManager
  ) {
    this.accountManager = accountManager
    this.monitoringManager = monitoringManager
    this.riskManager = riskManager
    this.legacyAccountManager = legacyAccountManager
  }

  /**
   * 注册交易所适配器
   */
  registerAdapter(exchange: string, adapter: ExchangeAdapter): void {
    this.adapters.set(exchange, adapter)
  }

  /**
   * 处理账户同步请求
   */
  async syncAccounts(request: AccountSyncRequest): Promise<AccountSyncResponse> {
    const response: AccountSyncResponse = {
      requestId: request.requestId,
      timestamp: new Date().toISOString(),
      results: [],
      errors: []
    }

    // 并发处理所有账户
    const syncPromises = request.accounts.map(account => 
      this.syncSingleAccount(account.accountId, account.exchange)
    )

    const syncResults = await Promise.allSettled(syncPromises)

    // 处理结果
    for (let i = 0; i < syncResults.length; i++) {
      const result = syncResults[i]
      const account = request.accounts[i]

      if (result.status === 'fulfilled') {
        response.results.push(result.value)
      } else {
        response.errors.push({
          accountId: account.accountId,
          code: 'SYNC_FAILED',
          message: result.reason?.message || 'Unknown error',
          retryable: true
        })

        // 生成监控事件
        this.monitoringManager.addEvent({
          eventId: `sync-error-${Date.now()}`,
          type: 'account-sync-fail',
          accountId: account.accountId,
          payload: {
            error: result.reason?.message,
            requestId: request.requestId
          },
          severity: 'WARN',
          createdAt: new Date()
        })
      }
    }

    return response
  }

  /**
   * 同步单个账户
   */
  private async syncSingleAccount(accountId: string, exchange: string): Promise<AccountSyncResponse['results'][0]> {
    try {
      logger.info(`同步账户 ${accountId} (${exchange})`)

      // 获取账户配置
      const account = this.accountManager.getAccount(accountId)
      if (!account) {
        throw new Error(`Account ${accountId} not found`)
      }

      // 获取交易所适配器
      const adapter = this.adapters.get(exchange)
      if (!adapter) {
        throw new Error(`No adapter found for exchange ${exchange}`)
      }

      // 获取账户信息
      const accountInfo = await adapter.getAccountInfo(accountId)
      
      // 计算利用率
      const utilization = this.accountManager.calculateUtilization(accountInfo.balances)

      // 更新现有 AccountManager 的状态
      await this.updateLegacyAccountState(accountId, accountInfo, utilization)

      // 更新风险指标
      this.updateRiskMetrics(accountId, accountInfo, utilization)

      logger.info(`账户 ${accountId} 同步成功，利用率: ${(utilization.value * 100).toFixed(2)}%`)

      return {
        accountId,
        status: 'success',
        balances: accountInfo.balances,
        positions: accountInfo.positions,
        utilization
      }
    } catch (error: any) {
      logger.error(`账户 ${accountId} 同步失败: ${error.message}`)
      throw new Error(`Failed to sync account ${accountId}: ${error.message}`)
    }
  }

  /**
   * 更新现有 AccountManager 的状态
   */
  private async updateLegacyAccountState(
    accountId: string, 
    accountInfo: any, 
    utilization: AccountUtilization
  ): Promise<void> {
    try {
      // 获取现有账户状态
      const existingState = this.legacyAccountManager.getAccountState(accountId)
      
      if (existingState) {
        // 更新余额信息
        const totalBalance = accountInfo.balances.reduce((sum: number, bal: AccountBalance) => 
          sum + parseFloat(bal.total), 0
        )
        const availableBalance = accountInfo.balances.reduce((sum: number, bal: AccountBalance) => 
          sum + parseFloat(bal.available), 0
        )

        // 更新状态
        existingState.lastBalance = totalBalance
        existingState.availableBalance = availableBalance
        existingState.marginUsed = totalBalance - availableBalance
        existingState.needsRebalance = !this.accountManager.isUtilizationInTarget(
          utilization, 
          this.accountManager.getAccount(accountId)!
        )

        // 更新仓位信息
        if (accountInfo.positions && accountInfo.positions.length > 0) {
          const position = accountInfo.positions[0] // 假设主要仓位
          existingState.entryPrice = parseFloat(position.entryPrice)
          existingState.unrealizedPnl = parseFloat(position.unrealizedPnl)
          existingState.currentPrice = parseFloat(position.markPrice)
          existingState.positionValue = parseFloat(position.size) * parseFloat(position.markPrice)
          existingState.netPosition = position.side === 'long' ? parseFloat(position.size) : -parseFloat(position.size)
        }

        logger.debug(`更新账户 ${accountId} 状态`, existingState)
      }
    } catch (error: any) {
      logger.warn(`更新现有账户状态失败: ${error.message}`)
    }
  }

  /**
   * 更新风险指标
   */
  private updateRiskMetrics(accountId: string, accountInfo: any, utilization: AccountUtilization): void {
    const envelope = this.riskManager.getEnvelopeByAccount(accountId)
    if (!envelope) return

    // 计算当前 Delta（简化版本）
    let currentDelta = 0
    for (const position of accountInfo.positions || []) {
      const size = parseFloat(position.size)
      const price = parseFloat(position.markPrice || position.entryPrice)
      const delta = position.side === 'long' ? size * price : -size * price
      currentDelta += delta
    }

    // 计算其他指标
    const totalBalance = accountInfo.balances.reduce((sum: number, bal: AccountBalance) => 
      sum + parseFloat(bal.total), 0
    )
    const availableBalance = accountInfo.balances.reduce((sum: number, bal: AccountBalance) => 
      sum + parseFloat(bal.available), 0
    )

    // 更新风险指标
    this.riskManager.updateMetrics({
      envelopeId: envelope.envelopeId,
      accountId,
      currentDelta,
      deltaDeviation: currentDelta, // 简化：假设目标 Delta 为 0
      currentUtilization: utilization.value,
      maxUtilization: Math.max(utilization.value, 0), // 简化
      currentDrawdown: 0, // 简化
      maxDrawdown: 0, // 简化
      currentLeverage: 1, // 简化
      maxLeverage: 1, // 简化
      slippage: 0, // 简化
      positionValue: totalBalance - availableBalance,
      availableBalance,
      totalBalance,
      timestamp: new Date()
    })

    // 检查风险状态
    const riskStatus = this.riskManager.checkRiskStatus(envelope.envelopeId)
    if (riskStatus.alerts.length > 0) {
      // 生成监控事件
      for (const alert of riskStatus.alerts) {
        this.monitoringManager.addEvent({
          eventId: `risk-alert-${Date.now()}`,
          type: 'delta-alert',
          accountId,
          payload: {
            alertType: alert.type,
            message: alert.message,
            severity: alert.severity
          },
          severity: alert.severity,
          createdAt: new Date()
        })
      }
    }
  }

  /**
   * 验证同步请求
   */
  validateSyncRequest(request: AccountSyncRequest): { isValid: boolean; errors: string[] } {
    const errors: string[] = []

    if (!request.requestId) {
      errors.push('requestId is required')
    }

    if (!request.accounts || request.accounts.length === 0) {
      errors.push('accounts array is required and cannot be empty')
    }

    for (let i = 0; i < request.accounts.length; i++) {
      const account = request.accounts[i]
      if (!account.accountId) {
        errors.push(`accounts[${i}].accountId is required`)
      }
      if (!account.exchange) {
        errors.push(`accounts[${i}].exchange is required`)
      }
      if (account.nonce === undefined) {
        errors.push(`accounts[${i}].nonce is required`)
      }
    }

    return {
      isValid: errors.length === 0,
      errors
    }
  }

  /**
   * 获取同步统计
   */
  getSyncStats(): {
    totalAccounts: number
    activeAccounts: number
    lastSyncTime: Date | null
    syncSuccessRate: number
  } {
    const accounts = this.accountManager.getAllAccounts()
    const totalAccounts = accounts.length
    const activeAccounts = accounts.filter(a => a.status === 'active').length
    
    // 简化统计
    return {
      totalAccounts,
      activeAccounts,
      lastSyncTime: new Date(),
      syncSuccessRate: 0.95 // 假设 95% 成功率
    }
  }

  /**
   * 批量同步所有账户
   */
  async syncAllAccounts(): Promise<AccountSyncResponse> {
    const accounts = this.accountManager.getAllAccounts()
    const request: AccountSyncRequest = {
      requestId: `batch-sync-${Date.now()}`,
      accounts: accounts.map(account => ({
        accountId: account.accountId,
        exchange: account.exchange,
        nonce: Date.now()
      }))
    }

    return this.syncAccounts(request)
  }

  /**
   * 同步指定交易所的所有账户
   */
  async syncAccountsByExchange(exchange: string): Promise<AccountSyncResponse> {
    const accounts = this.accountManager.getAccountsByExchange(exchange)
    const request: AccountSyncRequest = {
      requestId: `exchange-sync-${exchange}-${Date.now()}`,
      accounts: accounts.map(account => ({
        accountId: account.accountId,
        exchange: account.exchange,
        nonce: Date.now()
      }))
    }

    return this.syncAccounts(request)
  }
}
