/**
 * 账户管理器桥接服务
 * 连接现有 AccountManager 与新的 AccountSyncService
 * 实现 T029 任务：集成 AccountSyncService 与现有 AccountManager
 */
import { AccountManager } from '../modules/account/AccountManager.js'
import { AccountSyncService } from './AccountSyncService.js'
import { ExchangeAccountManager, ExchangeAccount, AccountBalance, AccountPosition } from '../models/ExchangeAccount.js'
import { MonitoringEventManager } from '../models/MonitoringEvent.js'
import { RiskEnvelopeManager } from '../models/RiskEnvelope.js'
import { AccountState } from '../modules/types.js'
import { logger } from '../utils/logger.js'

export interface BridgeConfig {
  syncInterval: number // 同步间隔，毫秒
  enableAutoSync: boolean // 是否启用自动同步
  batchSize: number // 批量同步账户数量
}

export class AccountManagerBridge {
  private syncInterval?: NodeJS.Timeout
  private isRunning = false
  private lastSyncTime = 0
  private syncStats = {
    totalSyncs: 0,
    successfulSyncs: 0,
    failedSyncs: 0,
    lastError: null as string | null
  }

  constructor(
    private legacyAccountManager: AccountManager,
    private accountSyncService: AccountSyncService,
    private exchangeAccountManager: ExchangeAccountManager,
    private monitoringManager: MonitoringEventManager,
    private riskManager: RiskEnvelopeManager,
    private config: BridgeConfig = {
      syncInterval: 30000, // 30秒同步一次
      enableAutoSync: true,
      batchSize: 10
    }
  ) {}

  /**
   * 启动桥接服务
   */
  async start(): Promise<void> {
    if (this.isRunning) {
      logger.warn('AccountManagerBridge 已在运行')
      return
    }

    logger.info('启动 AccountManagerBridge 服务')
    
    try {
      // 1. 初始化新架构的账户数据
      await this.initializeExchangeAccounts()
      
      // 2. 启动自动同步
      if (this.config.enableAutoSync) {
        this.startAutoSync()
      }
      
      this.isRunning = true
      logger.info('AccountManagerBridge 启动成功')
      
    } catch (error: any) {
      logger.error(`AccountManagerBridge 启动失败: ${error.message}`)
      throw error
    }
  }

  /**
   * 停止桥接服务
   */
  async stop(): Promise<void> {
    if (!this.isRunning) {
      return
    }

    logger.info('停止 AccountManagerBridge 服务')
    
    if (this.syncInterval) {
      clearInterval(this.syncInterval)
      this.syncInterval = undefined
    }
    
    this.isRunning = false
    logger.info('AccountManagerBridge 已停止')
  }

  /**
   * 获取桥接状态
   */
  getStatus(): {
    isRunning: boolean
    lastSyncTime: number
    syncStats: typeof this.syncStats
    config: BridgeConfig
  } {
    return {
      isRunning: this.isRunning,
      lastSyncTime: this.lastSyncTime,
      syncStats: { ...this.syncStats },
      config: { ...this.config }
    }
  }

  /**
   * 初始化新架构的账户数据
   */
  private async initializeExchangeAccounts(): Promise<void> {
    logger.info('初始化 ExchangeAccount 数据')

    const legacyAccounts = this.legacyAccountManager.getAccounts()
    const accountStates = this.legacyAccountManager.getAllAccountStates()

    for (let i = 0; i < legacyAccounts.length; i++) {
      const legacyAccount = legacyAccounts[i]
      const accountId = `pacifica-${i + 1}`
      const accountState = accountStates.get(accountId)

      if (!accountState) {
        logger.warn(`找不到账户状态: ${accountId}`)
        continue
      }

      // 创建新的 ExchangeAccount
      const exchangeAccount: ExchangeAccount = {
        accountId,
        exchange: 'pacifica',
        accountName: legacyAccount.name || `Pacifica Account ${i + 1}`,
        publicKey: legacyAccount.account,
        proxyProfile: 'default', // 默认代理配置
        utilizationTargetMin: 0.5,
        utilizationTargetMax: 0.8,
        deltaThreshold: 0.0005,
        maxPositionValue: 10000, // 默认最大仓位价值
        stopLossConfigId: 'default',
        status: 'active',
        createdAt: new Date(),
        updatedAt: new Date()
      }

      // 添加到新的账户管理器
      this.exchangeAccountManager.addAccount(exchangeAccount)

      // 创建对应的风险包络
      await this.createRiskEnvelope(accountId, exchangeAccount)

      logger.info(`初始化账户: ${accountId} (${exchangeAccount.accountName})`)
    }

    logger.info(`初始化完成，共处理 ${legacyAccounts.length} 个账户`)
  }

  /**
   * 创建风险包络
   */
  private async createRiskEnvelope(accountId: string, exchangeAccount: ExchangeAccount): Promise<void> {
    const riskEnvelope = {
      envelopeId: `envelope-${accountId}`,
      accountId,
      maxDrawdownPercent: 5.0, // 5% 最大回撤
      maxLeverage: 1.0, // 最大杠杆
      deltaThreshold: exchangeAccount.deltaThreshold,
      slippageTolerance: 0.001, // 0.1% 滑点容忍度
      emergencyStopLossSeconds: 30,
      createdAt: new Date(),
      updatedAt: new Date()
    }

    this.riskManager.addEnvelope(riskEnvelope)
    logger.debug(`创建风险包络: ${accountId}`)
  }

  /**
   * 启动自动同步
   */
  private startAutoSync(): void {
    logger.info(`启动自动同步，间隔: ${this.config.syncInterval}ms`)
    
    this.syncInterval = setInterval(async () => {
      try {
        await this.performSync()
      } catch (error: any) {
        logger.error(`自动同步失败: ${error.message}`)
        this.syncStats.failedSyncs++
        this.syncStats.lastError = error.message
      }
    }, this.config.syncInterval)

    // 立即执行一次同步
    this.performSync().catch(error => {
      logger.error(`初始同步失败: ${error.message}`)
    })
  }

  /**
   * 执行同步操作
   */
  async performSync(): Promise<void> {
    if (!this.isRunning) {
      return
    }

    logger.debug('开始执行账户同步')
    this.syncStats.totalSyncs++

    try {
      // 1. 从现有 AccountManager 获取最新状态
      const legacyAccounts = this.legacyAccountManager.getAccounts()
      const accountStates = this.legacyAccountManager.getAllAccountStates()

      // 2. 构建同步请求
      const syncRequest = {
        requestId: `sync-${Date.now()}`,
        accounts: legacyAccounts.map((_, index) => ({
          accountId: `pacifica-${index + 1}`,
          exchange: 'pacifica',
          nonce: Date.now()
        }))
      }

      // 3. 调用新的 AccountSyncService 进行同步
      const syncResponse = await this.accountSyncService.syncAccounts(syncRequest)

      // 4. 更新统计信息
      if (syncResponse.errors.length === 0) {
        this.syncStats.successfulSyncs++
        this.syncStats.lastError = null
      } else {
        this.syncStats.failedSyncs++
        this.syncStats.lastError = syncResponse.errors[0]?.message || 'Unknown error'
      }

      // 5. 记录同步结果
      this.lastSyncTime = Date.now()
      
      logger.info(`账户同步完成: ${syncResponse.results.length} 成功, ${syncResponse.errors.length} 失败`)

      // 6. 生成监控事件
      this.monitoringManager.addEvent({
        eventId: `bridge-sync-${Date.now()}`,
        type: 'account-sync-fail',
        payload: {
          requestId: syncRequest.requestId,
          totalAccounts: syncRequest.accounts.length,
          successfulAccounts: syncResponse.results.length,
          failedAccounts: syncResponse.errors.length,
          syncDuration: Date.now() - parseInt(syncRequest.requestId.split('-')[1])
        },
        severity: syncResponse.errors.length > 0 ? 'WARN' : 'INFO',
        createdAt: new Date()
      })

    } catch (error: any) {
      this.syncStats.failedSyncs++
      this.syncStats.lastError = error.message
      logger.error(`账户同步失败: ${error.message}`)
      throw error
    }
  }

  /**
   * 手动触发同步
   */
  async triggerManualSync(): Promise<{
    success: boolean
    message: string
    syncStats: typeof this.syncStats
  }> {
    try {
      await this.performSync()
      return {
        success: true,
        message: '手动同步完成',
        syncStats: { ...this.syncStats }
      }
    } catch (error: any) {
      return {
        success: false,
        message: `手动同步失败: ${error.message}`,
        syncStats: { ...this.syncStats }
      }
    }
  }

  /**
   * 获取桥接统计信息
   */
  getBridgeStats(): {
    legacyAccounts: number
    exchangeAccounts: number
    riskEnvelopes: number
    syncStats: typeof this.syncStats
    lastSyncTime: number
  } {
    return {
      legacyAccounts: this.legacyAccountManager.getAccounts().length,
      exchangeAccounts: this.exchangeAccountManager.getAllAccounts().length,
      riskEnvelopes: this.riskManager.getAllEnvelopes().length,
      syncStats: { ...this.syncStats },
      lastSyncTime: this.lastSyncTime
    }
  }

  /**
   * 更新配置
   */
  updateConfig(newConfig: Partial<BridgeConfig>): void {
    this.config = { ...this.config, ...newConfig }
    
    // 如果同步间隔改变，重启自动同步
    if (newConfig.syncInterval && this.isRunning) {
      this.stop().then(() => {
        this.start()
      })
    }
    
    logger.info('桥接配置已更新', newConfig)
  }

  /**
   * 双向数据同步：从新架构同步到现有系统
   */
  async syncToLegacy(): Promise<void> {
    logger.info('执行双向同步：新架构 → 现有系统')

    const exchangeAccounts = this.exchangeAccountManager.getAllAccounts()
    
    for (const exchangeAccount of exchangeAccounts) {
      const accountId = exchangeAccount.accountId
      const legacyState = this.legacyAccountManager.getAccountState(accountId)
      
      if (!legacyState) {
        logger.warn(`找不到现有账户状态: ${accountId}`)
        continue
      }

      // 这里可以根据需要从新的数据模型同步数据到现有系统
      // 例如：更新风险指标、利用率等
      
      logger.debug(`同步账户状态: ${accountId}`)
    }
  }
}
