/**
 * 🎯 Delta中性控制器 v2.0 - 企业级Delta中性控制平面
 *
 * 基于tasks规范重构的核心控制器，支持：
 * - Delta中性自动维持（±0.0005 BTC阈值）
 * - 资金利用率控制（50%-80%目标范围）
 * - 多平台多账户管理和认证
 * - 企业级风险包络集成
 * - 8秒控制循环和紧急干预
 * - 智能对冲执行和市场条件检查
 */

import { ExchangeAccount, ExchangeAccountConfig, AccountMetrics, DeltaControlParams } from '../models/ExchangeAccount'
import {
  RiskEnvelope,
  RiskEnvelopeConfig,
  RiskEnvelopeManager,
  RiskMetrics,
  ViolationEvent,
} from '../models/RiskEnvelope'
import UnifiedAccountManager from '../models/UnifiedAccountManager'
import { TradingService, ServiceStatus, AccountState } from '../modules/types'
import { logger } from '../shared/utils/logger'

/**
 * Delta中性控制计划
 */
export interface DeltaNeutralPlan {
  planId: string
  accountId: string
  trigger: 'delta-threshold' | 'utilization-deviation' | 'emergency-hedge' | 'manual-control'
  currentDelta: number
  targetDelta: number
  deltaThreshold: number
  riskEnvelopeId: string
  hedgeAccountId?: string
  priority: 'low' | 'medium' | 'high' | 'critical'
  maxExecutionTime: number
  createdAt: Date
}

/**
 * 多平台认证策略
 */
export interface MultiPlatformAuthStrategy {
  exchange: 'pacifica' | 'aster' | 'binance'
  authMethod: 'ed25519-signature' | 'eip191-signature' | 'hmac-sha256'
  credentialValidation: (config: ExchangeAccountConfig) => boolean
  proxyRequirement: boolean
  sessionManagement: boolean
}

/**
 * 对冲执行请求
 */
export interface HedgeExecutionRequest {
  planId: string
  primaryAccount: ExchangeAccount
  hedgeAccount?: ExchangeAccount
  symbol: string
  hedgeSize: number
  executionStrategy: 'market-orders' | 'limit-orders' | 'maker-taker-mixed'
  riskEnvelope: RiskEnvelope
  authStrategy: MultiPlatformAuthStrategy
  proxyProfile?: string
}

/**
 * Delta中性控制执行结果
 */
export interface DeltaNeutralExecutionResult {
  planId: string
  success: boolean
  controlCycleId: string
  accountId: string
  deltaBefore: number
  deltaAfter: number
  utilizationBefore: number
  utilizationAfter: number
  hedgeExecuted: boolean
  hedgeSize?: number
  riskViolations: ViolationEvent[]
  executionTimeMs: number
  timestamp: Date
  warnings: string[]
  errors: string[]
}

/**
 * 控制循环状态
 */
export interface ControlLoopState {
  cycleId: string
  isRunning: boolean
  lastExecution: Date
  nextExecution: Date
  intervalMs: number
  accountsMonitored: number
  successfulCycles: number
  failedCycles: number
}

/**
 * 资金利用率再平衡请求
 */
export interface UtilizationRebalanceRequest {
  accountId: string
  targetUtilization: number
  currentUtilization: number
  preserveDeltaNeutrality: boolean
  maxExecutionTime: number
}

/**
 * 资金利用率再平衡响应
 */
export interface UtilizationRebalanceResponse {
  success: boolean
  utilizationBefore: number
  utilizationAfter: number
  deltaImpact: number
  ordersExecuted: number
  executionTime: number
  warnings: string[]
}

type ServiceState =
  | 'stopped'
  | 'initializing'
  | 'initialized'
  | 'starting'
  | 'running'
  | 'stopping'
  | 'error'
  | 'emergency'

/**
 * DeltaNeutralController v2.0 - Delta中性控制平面核心控制器
 *
 * 核心职责：
 * 1. 维持全局Delta中性（±0.0005 BTC阈值）
 * 2. 管理资金利用率（50%-80%目标范围）
 * 3. 集成风险包络系统
 * 4. 支持多平台多账户认证
 * 5. 8秒控制循环自动化
 * 6. 紧急干预和止损机制
 */
export class DeltaNeutralController implements TradingService {
  private status: ServiceState = 'stopped'
  private lastStatusChange = Date.now()
  private controlLoopState: ControlLoopState
  private emergencyMode = false
  private controlLoopInterval?: NodeJS.Timeout

  // Delta中性控制配置
  private readonly deltaControlConfig = {
    deltaThreshold: 0.0005, // ±0.0005 BTC Delta阈值
    utilizationTargetMin: 0.5, // 50% 最小利用率目标
    utilizationTargetMax: 0.8, // 80% 最大利用率目标
    controlCycleInterval: 8000, // 8秒控制循环
    emergencyThreshold: 0.001, // 紧急对冲阈值（2倍Delta阈值）
    maxHedgeSize: 0.1, // 最大单次对冲大小
    maxExecutionTime: 30000, // 最大执行时间
    riskCheckInterval: 5000, // 5秒风险检查间隔
    emergencyStopLossTime: 30000, // 30秒紧急止损
  }

  // 多平台认证策略
  private readonly authStrategies: Map<string, MultiPlatformAuthStrategy> = new Map([
    [
      'pacifica',
      {
        exchange: 'pacifica',
        authMethod: 'ed25519-signature',
        credentialValidation: config => !!config.privateKey && config.privateKey.length === 64,
        proxyRequirement: true,
        sessionManagement: false,
      },
    ],
    [
      'aster',
      {
        exchange: 'aster',
        authMethod: 'eip191-signature',
        credentialValidation: config => !!config.privateKey && config.privateKey.startsWith('0x'),
        proxyRequirement: true,
        sessionManagement: true,
      },
    ],
    [
      'binance',
      {
        exchange: 'binance',
        authMethod: 'hmac-sha256',
        credentialValidation: config => !!config.publicKey && !!config.privateKey,
        proxyRequirement: false,
        sessionManagement: false,
      },
    ],
  ])

  constructor(
    private accountManager: UnifiedAccountManager,
    private riskEnvelopeManager: RiskEnvelopeManager,
  ) {
    this.controlLoopState = {
      cycleId: '',
      isRunning: false,
      lastExecution: new Date(),
      nextExecution: new Date(),
      intervalMs: this.deltaControlConfig.controlCycleInterval,
      accountsMonitored: 0,
      successfulCycles: 0,
      failedCycles: 0,
    }
  }

  /**
   * 初始化Delta中性控制器
   */
  async initialize(): Promise<void> {
    logger.info('🎯 DeltaNeutralController v2.0 初始化开始')
    this.status = 'initializing'
    this.lastStatusChange = Date.now()

    try {
      // 1. 验证多平台认证策略
      await this.validateMultiPlatformAuth()

      // 2. 初始化控制循环状态
      this.controlLoopState = {
        ...this.controlLoopState,
        cycleId: `cycle-${Date.now()}`,
        lastExecution: new Date(),
        nextExecution: new Date(Date.now() + this.deltaControlConfig.controlCycleInterval),
      }

      // 3. 检查所有账户的Delta和利用率状态
      await this.validateAccountStates()

      // 4. 初始化风险包络系统
      await this.initializeRiskEnvelopes()

      this.status = 'initialized'
      this.lastStatusChange = Date.now()
      logger.info('✅ DeltaNeutralController v2.0 初始化完成')
      logger.info(`📊 监控账户数: ${this.accountManager.getAllAccounts().length}`)
      logger.info(`🎯 Delta阈值: ±${this.deltaControlConfig.deltaThreshold} BTC`)
      logger.info(
        `📈 利用率目标: ${this.deltaControlConfig.utilizationTargetMin * 100}-${
          this.deltaControlConfig.utilizationTargetMax * 100
        }%`,
      )
    } catch (error) {
      this.status = 'error'
      this.lastStatusChange = Date.now()
      logger.error('❌ DeltaNeutralController 初始化失败:', error)
      throw error
    }
  }

  /**
   * 启动Delta中性控制器
   */
  async start(): Promise<void> {
    if (this.status !== 'initialized') {
      throw new Error('DeltaNeutralController 必须先初始化')
    }

    logger.info('🚀 DeltaNeutralController v2.0 启动中')
    this.status = 'starting'
    this.lastStatusChange = Date.now()

    try {
      // 1. 执行启动前检查
      await this.preStartupChecks()

      // 2. 启动控制循环
      this.startDeltaNeutralControlLoop()

      // 3. 启动风险监控循环
      this.startRiskMonitoringLoop()

      this.status = 'running'
      this.lastStatusChange = Date.now()
      this.controlLoopState.isRunning = true

      logger.info('✅ DeltaNeutralController v2.0 启动完成')
      logger.info(`🔄 控制循环间隔: ${this.deltaControlConfig.controlCycleInterval}ms`)
      logger.info(`🛡️ 风险检查间隔: ${this.deltaControlConfig.riskCheckInterval}ms`)
      logger.info('🎯 Delta中性控制平面已激活')
    } catch (error) {
      this.status = 'error'
      this.lastStatusChange = Date.now()
      logger.error('❌ DeltaNeutralController 启动失败:', error)
      throw error
    }
  }

  /**
   * 停止Delta中性控制器
   */
  async stop(): Promise<void> {
    logger.info('🛑 DeltaNeutralController v2.0 停止中')
    this.status = 'stopping'
    this.lastStatusChange = Date.now()

    try {
      // 1. 停止所有控制循环
      this.stopDeltaNeutralControlLoop()
      this.stopRiskMonitoringLoop()

      // 2. 执行紧急平仓（如果需要）
      if (this.emergencyMode) {
        await this.executeEmergencyShutdown()
      }

      // 3. 生成最终状态报告
      await this.generateShutdownReport()

      this.status = 'stopped'
      this.lastStatusChange = Date.now()
      this.controlLoopState.isRunning = false
      this.emergencyMode = false

      logger.info('✅ DeltaNeutralController v2.0 已安全停止')
      logger.info(`📊 成功周期: ${this.controlLoopState.successfulCycles}`)
      logger.info(`❌ 失败周期: ${this.controlLoopState.failedCycles}`)
    } catch (error) {
      this.status = 'error'
      this.lastStatusChange = Date.now()
      logger.error('❌ DeltaNeutralController 停止失败:', error)
      throw error
    }
  }

  /**
   * 执行Delta中性控制计划
   */
  async executeDeltaNeutralPlan(plan: DeltaNeutralPlan): Promise<DeltaNeutralExecutionResult> {
    const startTime = Date.now()
    const controlCycleId = `cycle-${Date.now()}-${plan.accountId}`
    logger.info(`🎯 [${controlCycleId}] 执行Delta中性控制计划`, {
      accountId: plan.accountId,
      trigger: plan.trigger,
      currentDelta: plan.currentDelta,
      targetDelta: plan.targetDelta,
    })

    try {
      // 1. 获取账户和风险包络
      const account = this.accountManager.getAccount(plan.accountId)
      if (!account) {
        throw new Error(`账户 ${plan.accountId} 未找到`)
      }

      const riskEnvelope = this.riskEnvelopeManager.getRiskEnvelope(plan.riskEnvelopeId)
      if (!riskEnvelope) {
        throw new Error(`风险包络 ${plan.riskEnvelopeId} 未找到`)
      }

      // 2. 执行风险预检查
      const preCheckViolations = await this.performRiskPreCheck(account, riskEnvelope, plan)
      if (preCheckViolations.length > 0) {
        logger.warn(`🚨 [${controlCycleId}] 风险预检查发现违规`, { violations: preCheckViolations.length })
      }

      // 3. 获取当前状态指标
      const metrics = account.getMetrics()
      const deltaBefore = metrics.currentDelta
      const utilizationBefore = metrics.currentUtilization

      // 4. 判断是否需要执行对冲
      const needsHedge = account.needsEmergencyHedge() || account.needsRebalance()
      let hedgeExecuted = false
      let hedgeSize = 0
      let deltaAfter = deltaBefore
      let utilizationAfter = utilizationBefore

      if (needsHedge) {
        // 5. 计算对冲大小
        hedgeSize = account.calculateHedgeSize()

        // 6. 执行对冲
        const hedgeResult = await this.executeHedge(account, hedgeSize, plan, riskEnvelope)
        hedgeExecuted = hedgeResult.success
        deltaAfter = hedgeResult.deltaAfter
        utilizationAfter = hedgeResult.utilizationAfter

        // 7. 更新账户指标
        account.updateMetrics({
          currentDelta: deltaAfter,
          currentUtilization: utilizationAfter,
          lastUpdate: new Date(),
        })
      }

      // 8. 执行风险后检查
      const postCheckViolations = await this.performRiskPostCheck(account, riskEnvelope)

      // 9. 生成执行结果
      const result: DeltaNeutralExecutionResult = {
        planId: plan.planId,
        success: true,
        controlCycleId,
        accountId: plan.accountId,
        deltaBefore,
        deltaAfter,
        utilizationBefore,
        utilizationAfter,
        hedgeExecuted,
        hedgeSize: hedgeExecuted ? hedgeSize : undefined,
        riskViolations: [...preCheckViolations, ...postCheckViolations],
        executionTimeMs: Date.now() - startTime,
        timestamp: new Date(),
        warnings: [],
        errors: [],
      }

      logger.info(`✅ [${controlCycleId}] Delta中性控制完成`, {
        deltaChange: (deltaAfter - deltaBefore).toFixed(6),
        utilizationChange: ((utilizationAfter - utilizationBefore) * 100).toFixed(1) + '%',
        hedgeExecuted,
        executionTime: result.executionTimeMs + 'ms',
      })

      return result
    } catch (error) {
      logger.error(`❌ [${controlCycleId}] Delta中性控制失败:`, error)

      return {
        planId: plan.planId,
        success: false,
        controlCycleId,
        accountId: plan.accountId,
        deltaBefore: plan.currentDelta,
        deltaAfter: plan.currentDelta,
        utilizationBefore: 0,
        utilizationAfter: 0,
        hedgeExecuted: false,
        riskViolations: [],
        executionTimeMs: Date.now() - startTime,
        timestamp: new Date(),
        warnings: [],
        errors: [error instanceof Error ? error.message : String(error)],
      }
    }
  }

  /**
   * 创建Delta中性控制计划
   */
  async createDeltaNeutralPlan(accountId: string, trigger: string): Promise<DeltaNeutralPlan> {
    const account = this.accountManager.getAccount(accountId)
    if (!account) {
      throw new Error(`账户 ${accountId} 未找到`)
    }

    const metrics = account.getMetrics()
    const config = account.getConfig()
    const deltaParams = account.getDeltaParams()

    const plan: DeltaNeutralPlan = {
      planId: `plan-${Date.now()}-${accountId}`,
      accountId,
      trigger: trigger as any,
      currentDelta: metrics.currentDelta,
      targetDelta: deltaParams.targetDelta,
      deltaThreshold: deltaParams.deltaThreshold,
      riskEnvelopeId: `risk-${accountId}`, // 简化实现
      priority: this.determinePriority(metrics.currentDelta, deltaParams.deltaThreshold),
      maxExecutionTime: this.deltaControlConfig.maxExecutionTime,
      createdAt: new Date(),
    }

    logger.info(`📋 [${plan.planId}] 创建Delta中性控制计划`, {
      trigger: plan.trigger,
      currentDelta: plan.currentDelta.toFixed(6),
      priority: plan.priority,
    })

    return plan
  }

  /**
   * 批量执行所有账户的Delta中性控制
   */
  async executeGlobalDeltaNeutralControl(): Promise<DeltaNeutralExecutionResult[]> {
    const accounts = this.accountManager.getActiveAccounts()
    const results: DeltaNeutralExecutionResult[] = []

    logger.info(`🌐 执行全局Delta中性控制，监控 ${accounts.length} 个账户`)

    for (const account of accounts) {
      try {
        const accountId = account.getConfig().accountId

        // 检查是否需要控制
        if (account.needsEmergencyHedge() || account.needsRebalance()) {
          const trigger = account.needsEmergencyHedge() ? 'emergency-hedge' : 'utilization-deviation'
          const plan = await this.createDeltaNeutralPlan(accountId, trigger)
          const result = await this.executeDeltaNeutralPlan(plan)
          results.push(result)

          // 紧急模式检查
          if (account.needsEmergencyHedge() && !result.success) {
            logger.error(`🚨 账户 ${accountId} 紧急对冲失败，进入紧急模式`)
            account.setEmergencyStatus(`紧急对冲失败: ${result.errors.join(', ')}`)
            this.emergencyMode = true
          }
        }
      } catch (error) {
        logger.error(`账户 ${account.getConfig().accountId} 控制失败:`, error)
      }
    }

    // 生成全局状态摘要
    await this.logGlobalSystemSummary(results)

    return results
  }

  /**
   * 获取服务状态
   */
  getStatus(): ServiceStatus {
    return {
      name: 'DeltaNeutralController',
      status: this.status === 'running' ? 'running' : this.status === 'error' ? 'error' : 'stopped',
      lastUpdate: this.lastStatusChange,
    }
  }

  getLastStatusChange(): number {
    return this.lastStatusChange
  }

  /**
   * 获取控制循环状态
   */
  getControlLoopState(): ControlLoopState {
    return { ...this.controlLoopState }
  }

  /**
   * 获取Delta控制配置
   */
  getDeltaControlConfig() {
    return { ...this.deltaControlConfig }
  }

  /**
   * 获取支持的认证策略
   */
  getSupportedAuthStrategies(): MultiPlatformAuthStrategy[] {
    return Array.from(this.authStrategies.values())
  }

  /**
   * 设置紧急模式
   */
  setEmergencyMode(enabled: boolean, reason?: string): void {
    this.emergencyMode = enabled
    if (enabled) {
      this.status = 'emergency'
      logger.error(`🚨 DeltaNeutralController 进入紧急模式: ${reason || '未知原因'}`)
    } else {
      this.status = 'running'
      logger.info('✅ DeltaNeutralController 退出紧急模式')
    }
    this.lastStatusChange = Date.now()
  }

  // ========== 私有方法 ==========

  private riskMonitoringInterval?: NodeJS.Timeout

  /**
   * 启动Delta中性控制循环
   */
  private startDeltaNeutralControlLoop(): void {
    this.controlLoopInterval = setInterval(async () => {
      try {
        this.controlLoopState.cycleId = `cycle-${Date.now()}`
        this.controlLoopState.lastExecution = new Date()
        this.controlLoopState.nextExecution = new Date(Date.now() + this.deltaControlConfig.controlCycleInterval)

        const results = await this.executeGlobalDeltaNeutralControl()

        if (results.every(r => r.success)) {
          this.controlLoopState.successfulCycles++
        } else {
          this.controlLoopState.failedCycles++
        }
      } catch (error) {
        logger.error('❌ Delta中性控制循环失败:', error)
        this.controlLoopState.failedCycles++
      }
    }, this.deltaControlConfig.controlCycleInterval)

    logger.info(`🔄 Delta中性控制循环已启动，间隔 ${this.deltaControlConfig.controlCycleInterval}ms`)
  }

  /**
   * 停止Delta中性控制循环
   */
  private stopDeltaNeutralControlLoop(): void {
    if (this.controlLoopInterval) {
      clearInterval(this.controlLoopInterval)
      this.controlLoopInterval = undefined
      logger.info('🛑 Delta中性控制循环已停止')
    }
  }

  /**
   * 启动风险监控循环
   */
  private startRiskMonitoringLoop(): void {
    this.riskMonitoringInterval = setInterval(async () => {
      try {
        await this.performGlobalRiskCheck()
      } catch (error) {
        logger.error('❌ 风险监控循环失败:', error)
      }
    }, this.deltaControlConfig.riskCheckInterval)

    logger.info(`🛡️ 风险监控循环已启动，间隔 ${this.deltaControlConfig.riskCheckInterval}ms`)
  }

  /**
   * 停止风险监控循环
   */
  private stopRiskMonitoringLoop(): void {
    if (this.riskMonitoringInterval) {
      clearInterval(this.riskMonitoringInterval)
      this.riskMonitoringInterval = undefined
      logger.info('🛑 风险监控循环已停止')
    }
  }

  /**
   * 验证多平台认证策略
   */
  private async validateMultiPlatformAuth(): Promise<void> {
    const accounts = this.accountManager.getAllAccounts()

    for (const account of accounts) {
      const config = account.getConfig()
      const authStrategy = this.authStrategies.get(config.exchange)

      if (!authStrategy) {
        throw new Error(`不支持的交易所: ${config.exchange}`)
      }

      if (!authStrategy.credentialValidation(config)) {
        throw new Error(`账户 ${config.accountId} 认证凭据验证失败`)
      }
    }

    logger.info(`✅ 验证了 ${accounts.length} 个账户的多平台认证策略`)
  }

  /**
   * 验证账户状态
   */
  private async validateAccountStates(): Promise<void> {
    const accounts = this.accountManager.getAllAccounts()

    for (const account of accounts) {
      const metrics = account.getMetrics()
      const config = account.getConfig()

      // 检查基本状态
      if (config.status !== 'active') {
        logger.warn(`⚠️ 账户 ${config.accountId} 状态不是 active: ${config.status}`)
      }

      // 检查Delta阈值
      if (Math.abs(metrics.currentDelta) > this.deltaControlConfig.emergencyThreshold) {
        logger.warn(`🚨 账户 ${config.accountId} Delta超过紧急阈值: ${metrics.currentDelta}`)
      }

      // 检查利用率
      if (
        metrics.currentUtilization < this.deltaControlConfig.utilizationTargetMin ||
        metrics.currentUtilization > this.deltaControlConfig.utilizationTargetMax
      ) {
        logger.warn(`⚠️ 账户 ${config.accountId} 利用率超出目标范围: ${(metrics.currentUtilization * 100).toFixed(1)}%`)
      }
    }

    logger.info(`📊 验证了 ${accounts.length} 个账户的状态`)
  }

  /**
   * 初始化风险包络系统
   */
  private async initializeRiskEnvelopes(): Promise<void> {
    const accounts = this.accountManager.getAllAccounts()

    for (const account of accounts) {
      const config = account.getConfig()

      // 检查是否已有风险包络
      const existingEnvelope = this.riskEnvelopeManager.getRiskEnvelopeByAccount(config.accountId)

      if (!existingEnvelope) {
        // 创建默认风险包络
        const riskConfig: RiskEnvelopeConfig = {
          envelopeId: `risk-${config.accountId}`,
          accountId: config.accountId,
          maxDrawdownPercent: 5.0,
          maxLeverage: 10.0,
          maxPositionSize: config.maxPositionValue,
          stopLossPercent: 3.0,
          liquidationBuffer: 2.0,
          riskBudgetUsd: config.maxPositionValue * 0.1,
          enabled: true,
        }

        this.riskEnvelopeManager.createRiskEnvelope(riskConfig)
        logger.info(`🛡️ 为账户 ${config.accountId} 创建默认风险包络`)
      }
    }
  }

  /**
   * 执行启动前检查
   */
  private async preStartupChecks(): Promise<void> {
    // 1. 检查紧急状态账户
    const emergencyAccounts = this.accountManager
      .getAllAccounts()
      .filter(account => account.getConfig().status === 'emergency')

    if (emergencyAccounts.length > 0) {
      logger.warn(`⚠️ 发现 ${emergencyAccounts.length} 个紧急状态账户，将优先处理`)
      this.emergencyMode = true
    }

    // 2. 检查全局Delta风险
    const globalDelta = this.accountManager.calculateGlobalDelta()
    if (Math.abs(globalDelta) > this.deltaControlConfig.emergencyThreshold) {
      logger.warn(`🚨 全局Delta超过紧急阈值: ${globalDelta.toFixed(6)} BTC`)
    }

    // 3. 验证风险包络完整性
    const accountsWithoutRisk = this.accountManager
      .getAllAccounts()
      .filter(account => !this.riskEnvelopeManager.getRiskEnvelopeByAccount(account.getConfig().accountId))

    if (accountsWithoutRisk.length > 0) {
      throw new Error(`${accountsWithoutRisk.length} 个账户缺少风险包络配置`)
    }

    logger.info('✅ 启动前检查通过')
  }

  /**
   * 执行全局风险检查
   */
  private async performGlobalRiskCheck(): Promise<void> {
    const accounts = this.accountManager.getAllAccounts()
    let totalViolations = 0

    for (const account of accounts) {
      const riskEnvelope = this.riskEnvelopeManager.getRiskEnvelopeByAccount(account.getConfig().accountId)
      if (riskEnvelope) {
        const violations = riskEnvelope.checkViolations()
        totalViolations += violations.length

        if (violations.length > 0) {
          logger.warn(`🛡️ 账户 ${account.getConfig().accountId} 发现 ${violations.length} 个风险违规`)
        }
      }
    }

    if (totalViolations > 0) {
      logger.warn(`🚨 全局风险检查发现 ${totalViolations} 个违规事件`)
    }
  }

  /**
   * 执行风险预检查
   */
  private async performRiskPreCheck(
    account: ExchangeAccount,
    riskEnvelope: RiskEnvelope,
    plan: DeltaNeutralPlan,
  ): Promise<ViolationEvent[]> {
    const violations: ViolationEvent[] = []
    const metrics = account.getMetrics()

    // 检查账户状态
    if (account.getConfig().status !== 'active') {
      violations.push({
        violationId: `check-${Date.now()}-status`,
        envelopeId: riskEnvelope.getConfig().envelopeId,
        violationType: 'account-inactive',
        severity: 'HIGH',
        message: '账户状态不是活跃状态',
        threshold: 'active',
        actualValue: account.getConfig().status,
        timestamp: new Date(),
      })
    }

    // 检查Delta风险
    if (Math.abs(metrics.currentDelta) > this.deltaControlConfig.emergencyThreshold) {
      violations.push({
        violationId: `check-${Date.now()}-delta`,
        envelopeId: riskEnvelope.getConfig().envelopeId,
        violationType: 'delta-emergency',
        severity: 'CRITICAL',
        message: 'Delta敞口超过紧急阈值',
        threshold: this.deltaControlConfig.emergencyThreshold,
        actualValue: Math.abs(metrics.currentDelta),
        timestamp: new Date(),
      })
    }

    return violations
  }

  /**
   * 执行风险后检查
   */
  private async performRiskPostCheck(account: ExchangeAccount, riskEnvelope: RiskEnvelope): Promise<ViolationEvent[]> {
    // 更新风险包络指标
    const metrics = account.getMetrics()
    riskEnvelope.updateMetrics({
      currentDrawdown: 0, // 需要计算
      currentLeverage: metrics.leverage || 1,
      currentPositionSize: Math.abs(metrics.netPosition),
      dailyPnl: metrics.unrealizedPnl || 0,
      riskScore: 0, // 会自动计算
    })

    // 检查违规
    return riskEnvelope.checkViolations()
  }

  /**
   * 执行对冲
   */
  private async executeHedge(
    account: ExchangeAccount,
    hedgeSize: number,
    plan: DeltaNeutralPlan,
    riskEnvelope: RiskEnvelope,
  ): Promise<{ success: boolean; deltaAfter: number; utilizationAfter: number }> {
    const config = account.getConfig()
    const authStrategy = this.authStrategies.get(config.exchange)

    if (!authStrategy) {
      throw new Error(`不支持的交易所认证: ${config.exchange}`)
    }

    logger.info(`🔄 执行对冲`, {
      accountId: config.accountId,
      exchange: config.exchange,
      hedgeSize: hedgeSize.toFixed(6),
      authMethod: authStrategy.authMethod,
    })

    try {
      // 模拟对冲执行（实际实现需要调用交易接口）
      const deltaAfter = account.getMetrics().currentDelta - hedgeSize
      const utilizationAdjustment = account.calculateUtilizationAdjustment()
      const utilizationAfter = account.getMetrics().currentUtilization + utilizationAdjustment

      // 记录对冲历史
      logger.info(`✅ 对冲执行完成`, {
        accountId: config.accountId,
        deltaChange: (-hedgeSize).toFixed(6),
        deltaAfter: deltaAfter.toFixed(6),
        utilizationAfter: (utilizationAfter * 100).toFixed(1) + '%',
      })

      return {
        success: true,
        deltaAfter,
        utilizationAfter,
      }
    } catch (error) {
      logger.error(`❌ 对冲执行失败:`, error)
      return {
        success: false,
        deltaAfter: account.getMetrics().currentDelta,
        utilizationAfter: account.getMetrics().currentUtilization,
      }
    }
  }

  /**
   * 确定计划优先级
   */
  private determinePriority(currentDelta: number, deltaThreshold: number): 'low' | 'medium' | 'high' | 'critical' {
    const deltaRatio = Math.abs(currentDelta) / deltaThreshold

    if (deltaRatio >= 2.0) return 'critical'
    if (deltaRatio >= 1.5) return 'high'
    if (deltaRatio >= 1.0) return 'medium'
    return 'low'
  }

  /**
   * 生成全局系统摘要日志
   */
  private async logGlobalSystemSummary(results: DeltaNeutralExecutionResult[]): Promise<void> {
    const totalAccounts = this.accountManager.getAllAccounts().length
    const activeAccounts = this.accountManager.getActiveAccounts().length
    const needingHedge = this.accountManager.getAccountsNeedingHedge().length
    const globalDelta = this.accountManager.calculateGlobalDelta()
    const globalUtilization = this.accountManager.calculateGlobalUtilization()

    const successfulExecutions = results.filter(r => r.success).length
    const failedExecutions = results.filter(r => !r.success).length
    const totalViolations = results.reduce((sum, r) => sum + r.riskViolations.length, 0)

    logger.info('📊 全局Delta中性控制摘要', {
      accounts: {
        total: totalAccounts,
        active: activeAccounts,
        needingHedge: needingHedge,
      },
      global: {
        delta: globalDelta.toFixed(6) + ' BTC',
        utilization: (globalUtilization * 100).toFixed(1) + '%',
      },
      execution: {
        successful: successfulExecutions,
        failed: failedExecutions,
        riskViolations: totalViolations,
      },
      controlLoop: {
        cycleId: this.controlLoopState.cycleId,
        successfulCycles: this.controlLoopState.successfulCycles,
        failedCycles: this.controlLoopState.failedCycles,
      },
      emergencyMode: this.emergencyMode,
    })
  }

  /**
   * 执行紧急关闭
   */
  private async executeEmergencyShutdown(): Promise<void> {
    logger.error('🚨 执行紧急关闭程序')

    const emergencyAccounts = this.accountManager
      .getAllAccounts()
      .filter(account => account.getConfig().status === 'emergency')

    for (const account of emergencyAccounts) {
      try {
        // 执行紧急平仓（简化实现）
        account.resetToActive()
        logger.info(`✅ 账户 ${account.getConfig().accountId} 紧急处理完成`)
      } catch (error) {
        logger.error(`❌ 账户 ${account.getConfig().accountId} 紧急处理失败:`, error)
      }
    }
  }

  /**
   * 生成关闭报告
   */
  private async generateShutdownReport(): Promise<void> {
    const systemSummary = this.accountManager.getSystemSummary()

    logger.info('📋 DeltaNeutralController 关闭报告', {
      runtime: {
        successfulCycles: this.controlLoopState.successfulCycles,
        failedCycles: this.controlLoopState.failedCycles,
        totalCycles: this.controlLoopState.successfulCycles + this.controlLoopState.failedCycles,
      },
      finalState: {
        totalAccounts: systemSummary.totalAccounts,
        activeAccounts: systemSummary.activeAccounts,
        accountsNeedingHedge: systemSummary.accountsNeedingHedge,
        globalDelta: systemSummary.globalDelta.toFixed(6) + ' BTC',
        globalUtilization: (systemSummary.globalUtilization * 100).toFixed(1) + '%',
      },
      emergencyMode: this.emergencyMode,
    })
  }
}
