#!/usr/bin/env node

/**
 * 🧪 统一架构测试脚本
 * 验证新旧架构的完全统一和生产环境兼容性
 */

import { SystemOrchestrator } from './src/modules/SystemOrchestrator.js'
import { UnifiedTradingSystem } from './src/main-production.js'
import { DevelopmentTradingSystem } from './src/core/app.js'
import { logger } from './src/utils/logger.js'
import * as dotenv from 'dotenv'

// 加载环境变量
dotenv.config()

interface TestResult {
  name: string
  status: 'PASS' | 'FAIL' | 'SKIP'
  duration: number
  details?: string
  error?: string
}

class UnifiedArchitectureTestSuite {
  private results: TestResult[] = []

  /**
   * 运行完整的统一架构测试套件
   */
  async runAllTests(): Promise<void> {
    console.log('🧪 开始统一架构测试套件')
    console.log('=' + '='.repeat(60))

    await this.testSystemOrchestratorIntegration()
    await this.testProductionSystemCompatibility()
    await this.testDevelopmentSystemCompatibility()
    await this.testDeltaNeutralControllerIntegration()
    await this.testRiskMonitoringServiceIntegration()
    await this.testServiceLifecycleManagement()
    await this.testBackwardCompatibility()

    this.printTestResults()
  }

  /**
   * 测试SystemOrchestrator集成
   */
  private async testSystemOrchestratorIntegration(): Promise<void> {
    const testName = 'SystemOrchestrator 集成测试'
    const startTime = Date.now()

    try {
      logger.info('🧪 测试 SystemOrchestrator 集成...')

      const orchestrator = new SystemOrchestrator()

      // 初始化系统服务
      await orchestrator.initialize({
        accounts: [],
        enableTrading: false,
        enableDashboard: false,
        enableControlPlane: false
      })

      // 验证服务注册
      const services = await orchestrator.getSystemStatus()

      if (!services || typeof services !== 'object') {
        throw new Error('SystemOrchestrator 状态获取失败')
      }

      // 验证核心服务存在
      const requiredServices = [
        'AccountManager',
        'RiskManager',
        'TradingEngine',
        'DashboardService'
      ]

      for (const serviceName of requiredServices) {
        if (!services.services || !services.services[serviceName]) {
          throw new Error(`必需服务未注册: ${serviceName}`)
        }
      }

      this.results.push({
        name: testName,
        status: 'PASS',
        duration: Date.now() - startTime,
        details: `验证了 ${Object.keys(services.services).length} 个服务`
      })

    } catch (error) {
      this.results.push({
        name: testName,
        status: 'FAIL',
        duration: Date.now() - startTime,
        error: error instanceof Error ? error.message : String(error)
      })
    }
  }

  /**
   * 测试生产环境系统兼容性
   */
  private async testProductionSystemCompatibility(): Promise<void> {
    const testName = '生产环境系统兼容性'
    const startTime = Date.now()

    try {
      logger.info('🧪 测试生产环境系统兼容性...')

      // 测试生产环境配置验证
      const originalEnv = process.env.NODE_ENV
      process.env.NODE_ENV = 'production'

      // 验证生产环境类可以实例化
      const productionSystem = new UnifiedTradingSystem()

      if (!productionSystem) {
        throw new Error('生产环境系统实例化失败')
      }

      // 恢复环境变量
      process.env.NODE_ENV = originalEnv

      this.results.push({
        name: testName,
        status: 'PASS',
        duration: Date.now() - startTime,
        details: '生产环境系统类实例化成功'
      })

    } catch (error) {
      this.results.push({
        name: testName,
        status: 'FAIL',
        duration: Date.now() - startTime,
        error: error instanceof Error ? error.message : String(error)
      })
    }
  }

  /**
   * 测试开发环境系统兼容性
   */
  private async testDevelopmentSystemCompatibility(): Promise<void> {
    const testName = '开发环境系统兼容性'
    const startTime = Date.now()

    try {
      logger.info('🧪 测试开发环境系统兼容性...')

      // 验证开发环境类可以实例化
      const developmentSystem = new DevelopmentTradingSystem()

      if (!developmentSystem) {
        throw new Error('开发环境系统实例化失败')
      }

      // 测试开发环境状态获取
      const status = await developmentSystem.getStatus()

      if (!status || !status.environment || status.environment !== 'development') {
        throw new Error('开发环境状态获取失败')
      }

      this.results.push({
        name: testName,
        status: 'PASS',
        duration: Date.now() - startTime,
        details: `开发环境状态: ${status.status}`
      })

    } catch (error) {
      this.results.push({
        name: testName,
        status: 'FAIL',
        duration: Date.now() - startTime,
        error: error instanceof Error ? error.message : String(error)
      })
    }
  }

  /**
   * 测试DeltaNeutralController集成
   */
  private async testDeltaNeutralControllerIntegration(): Promise<void> {
    const testName = 'DeltaNeutralController 集成'
    const startTime = Date.now()

    try {
      logger.info('🧪 测试 DeltaNeutralController 集成...')

      // 验证DeltaNeutralController文件存在
      const { DeltaNeutralController } = await import('./src/controllers/DeltaNeutralController.js')

      if (!DeltaNeutralController) {
        throw new Error('DeltaNeutralController 导入失败')
      }

      this.results.push({
        name: testName,
        status: 'PASS',
        duration: Date.now() - startTime,
        details: 'DeltaNeutralController 成功集成'
      })

    } catch (error) {
      this.results.push({
        name: testName,
        status: 'FAIL',
        duration: Date.now() - startTime,
        error: error instanceof Error ? error.message : String(error)
      })
    }
  }

  /**
   * 测试RiskMonitoringService集成
   */
  private async testRiskMonitoringServiceIntegration(): Promise<void> {
    const testName = 'RiskMonitoringService 集成'
    const startTime = Date.now()

    try {
      logger.info('🧪 测试 RiskMonitoringService 集成...')

      // 验证RiskMonitoringService文件存在
      const { RiskMonitoringService } = await import('./src/services/RiskMonitoringService.js')

      if (!RiskMonitoringService) {
        throw new Error('RiskMonitoringService 导入失败')
      }

      this.results.push({
        name: testName,
        status: 'PASS',
        duration: Date.now() - startTime,
        details: 'RiskMonitoringService 成功集成'
      })

    } catch (error) {
      this.results.push({
        name: testName,
        status: 'FAIL',
        duration: Date.now() - startTime,
        error: error instanceof Error ? error.message : String(error)
      })
    }
  }

  /**
   * 测试服务生命周期管理
   */
  private async testServiceLifecycleManagement(): Promise<void> {
    const testName = '服务生命周期管理'
    const startTime = Date.now()

    try {
      logger.info('🧪 测试服务生命周期管理...')

      const orchestrator = new SystemOrchestrator()

      // 测试系统状态获取（不启动实际服务）
      const initialStatus = await orchestrator.getSystemStatus()

      if (!initialStatus || (initialStatus.status !== 'stopped' && initialStatus.status !== 'initialized')) {
        throw new Error(`初始状态应为 stopped 或 initialized，当前为: ${initialStatus.status}`)
      }

      this.results.push({
        name: testName,
        status: 'PASS',
        duration: Date.now() - startTime,
        details: `初始状态: ${initialStatus.status}`
      })

    } catch (error) {
      this.results.push({
        name: testName,
        status: 'FAIL',
        duration: Date.now() - startTime,
        error: error instanceof Error ? error.message : String(error)
      })
    }
  }

  /**
   * 测试向后兼容性
   */
  private async testBackwardCompatibility(): Promise<void> {
    const testName = '向后兼容性'
    const startTime = Date.now()

    try {
      logger.info('🧪 测试向后兼容性...')

      // 验证main.ts导出的向后兼容函数
      const mainModule = await import('./src/main.js')

      // 检查向后兼容导出
      if (typeof mainModule.greeter !== 'function') {
        throw new Error('向后兼容函数 greeter 不存在')
      }

      // 测试向后兼容函数
      const greeting = await mainModule.greeter('统一架构')

      if (!greeting || !greeting.includes('统一架构')) {
        throw new Error('向后兼容函数返回值不正确')
      }

      this.results.push({
        name: testName,
        status: 'PASS',
        duration: Date.now() - startTime,
        details: `兼容性测试: ${greeting}`
      })

    } catch (error) {
      this.results.push({
        name: testName,
        status: 'FAIL',
        duration: Date.now() - startTime,
        error: error instanceof Error ? error.message : String(error)
      })
    }
  }

  /**
   * 打印测试结果
   */
  private printTestResults(): void {
    console.log('\n' + '🧪 统一架构测试结果')
    console.log('=' + '='.repeat(60))

    let passCount = 0
    let failCount = 0
    let totalDuration = 0

    this.results.forEach(result => {
      const statusIcon = result.status === 'PASS' ? '✅' : result.status === 'FAIL' ? '❌' : '⏭️'
      console.log(`${statusIcon} ${result.name} (${result.duration}ms)`)

      if (result.details) {
        console.log(`   📋 ${result.details}`)
      }

      if (result.error) {
        console.log(`   ❌ ${result.error}`)
      }

      if (result.status === 'PASS') passCount++
      if (result.status === 'FAIL') failCount++
      totalDuration += result.duration
    })

    console.log('\n' + '📊 测试统计')
    console.log('=' + '='.repeat(60))
    console.log(`✅ 通过: ${passCount}`)
    console.log(`❌ 失败: ${failCount}`)
    console.log(`⏭️ 跳过: ${this.results.length - passCount - failCount}`)
    console.log(`⏱️ 总时间: ${totalDuration}ms`)
    console.log(`📈 成功率: ${((passCount / this.results.length) * 100).toFixed(1)}%`)

    if (failCount === 0) {
      console.log('\n🎉 所有测试通过！统一架构验证成功！')
    } else {
      console.log('\n⚠️ 有测试失败，需要修复后再进行生产环境部署')
    }
  }
}

/**
 * 主测试函数
 */
async function main(): Promise<void> {
  try {
    const testSuite = new UnifiedArchitectureTestSuite()
    await testSuite.runAllTests()
  } catch (error) {
    console.error('💥 测试套件执行失败:', error)
    process.exit(1)
  }
}

// 如果直接运行此文件，启动测试
if (import.meta.url === `file://${process.argv[1]}`) {
  main().catch(error => {
    console.error('💥 测试失败:', error)
    process.exit(1)
  })
}