/**
 * 对冲执行服务
 * 基于 contracts/hedge-execution.md 的规范实现
 * 集成现有的交易执行器和风险管理器
 */
import { 
  HedgeExecutionResponse, 
  HedgeExecution, 
  HedgeOrder,
  HedgeExecutionManager 
} from '../models/HedgeExecution.js'

// 定义对冲执行请求接口
export interface HedgeExecutionRequest {
  executionId: string
  primaryAccountId: string
  hedgeAccountId: string
  deltaBefore: number
  targetDelta: number
  symbol?: string
  triggerReason: 'utilization' | 'delta' | 'failover' | 'manual'
  proxyProfile?: string
}
import { AccountManager } from '../modules/account/AccountManager.js'
import { RiskEnvelopeManager } from '../models/RiskEnvelope.js'
import { TradingSignal } from '../modules/types.js'
import { logger } from '../utils/logger.js'

export interface OrderExecutor {
  executeOrder(signal: TradingSignal): Promise<{
    success: boolean
    orderId?: string
    filledSize?: string
    avgPrice?: string
    fees?: string
    error?: string
  }>
}

export class HedgeExecutionService {
  private hedgeManager: HedgeExecutionManager
  private accountManager: AccountManager
  private riskManager: RiskEnvelopeManager
  private orderExecutor: OrderExecutor

  constructor(
    hedgeManager: HedgeExecutionManager,
    accountManager: AccountManager,
    riskManager: RiskEnvelopeManager,
    orderExecutor: OrderExecutor
  ) {
    this.hedgeManager = hedgeManager
    this.accountManager = accountManager
    this.riskManager = riskManager
    this.orderExecutor = orderExecutor
  }

  /**
   * 执行对冲请求
   */
  async executeHedge(request: HedgeExecutionRequest): Promise<HedgeExecutionResponse> {
    const startTime = Date.now()
    logger.info(`开始执行对冲: ${request.executionId}`, {
      primaryAccountId: request.primaryAccountId,
      hedgeAccountId: request.hedgeAccountId,
      deltaBefore: request.deltaBefore,
      targetDelta: request.targetDelta
    })

    try {
      // 验证请求
      const validation = this.validateHedgeRequest(request)
      if (!validation.isValid) {
        throw new Error(`Invalid hedge request: ${validation.errors.join(', ')}`)
      }

      // 计算需要的对冲量
      const hedgeAmount = request.deltaBefore - request.targetDelta
      const hedgeSide = hedgeAmount > 0 ? 'sell' : 'buy'
      const hedgeSize = Math.abs(hedgeAmount)

      // 创建对冲执行记录
      const execution: HedgeExecution = {
        executionId: request.executionId,
        primaryAccountId: request.primaryAccountId,
        hedgeAccountId: request.hedgeAccountId,
        deltaBefore: request.deltaBefore,
        deltaAfter: request.targetDelta,
        orders: [],
        triggerReason: request.triggerReason,
        durationMs: 0,
        result: 'fail',
        createdAt: new Date()
      }

      this.hedgeManager.createExecution(execution)

      // 生成对冲订单
      const hedgeOrders = await this.generateHedgeOrders(
        request.primaryAccountId,
        request.hedgeAccountId,
        hedgeSide,
        hedgeSize,
        request.symbol || 'BTC',
        request.proxyProfile
      )

      // 执行对冲订单
      const executionResults = await this.executeHedgeOrders(hedgeOrders)
      
      // 更新执行记录
      execution.orders = executionResults
      execution.durationMs = Date.now() - startTime

      // 计算最终 Delta
      const finalDelta = await this.calculateFinalDelta(
        request.primaryAccountId,
        request.hedgeAccountId,
        executionResults
      )
      
      execution.deltaAfter = finalDelta

      // 确定执行结果
      const deltaDiff = Math.abs(finalDelta - request.targetDelta)
      if (deltaDiff <= 0.001) { // 允许 0.001 BTC 的误差
        execution.result = 'success'
      } else if (deltaDiff <= Math.abs(hedgeAmount) * 0.5) {
        execution.result = 'partial'
      } else {
        execution.result = 'fail'
      }

      this.hedgeManager.updateExecutionResult(
        execution.executionId,
        execution.result,
        execution.durationMs
      )

      // 构建响应
      const response: HedgeExecutionResponse = {
        executionId: execution.executionId,
        status: execution.result === 'success' ? 'completed' : execution.result === 'fail' ? 'failed' : 'partial',
        deltaAfter: finalDelta,
        executionDetails: executionResults,
        durationMs: execution.durationMs,
        alerts: this.generateExecutionAlerts(execution, executionResults),
        completedAt: new Date()
      }

      logger.info(`对冲执行完成: ${execution.result}`, {
        executionId: execution.executionId,
        deltaBefore: request.deltaBefore,
        deltaAfter: finalDelta,
        durationMs: execution.durationMs
      })

      return response

    } catch (error: any) {
      const durationMs = Date.now() - startTime
      logger.error(`对冲执行失败: ${error.message}`, {
        executionId: request.executionId,
        durationMs
      })

      // 更新执行记录为失败
      this.hedgeManager.updateExecutionResult(request.executionId, 'fail', durationMs)

      return {
        executionId: request.executionId,
        status: 'failed',
        deltaAfter: request.deltaBefore, // 失败时 Delta 不变
        executionDetails: [],
        durationMs,
        alerts: [{
          type: 'execution-error',
          message: error.message,
          severity: 'CRITICAL'
        }],
        completedAt: new Date()
      }
    }
  }

  /**
   * 生成对冲订单
   */
  private async generateHedgeOrders(
    primaryAccountId: string,
    hedgeAccountId: string,
    hedgeSide: 'buy' | 'sell',
    hedgeSize: number,
    symbol: string,
    proxyProfile?: string
  ): Promise<HedgeOrder[]> {
    const orders: HedgeOrder[] = []

    // 主账户订单
    const primaryOrder: HedgeOrder = {
      accountId: primaryAccountId,
      side: hedgeSide,
      type: 'market', // 使用市价单确保快速执行
      amount: hedgeSize.toString(),
      proxyProfile
    }

    // 对冲账户订单（反向）
    const hedgeOrder: HedgeOrder = {
      accountId: hedgeAccountId,
      side: hedgeSide === 'buy' ? 'sell' : 'buy',
      type: 'market',
      amount: hedgeSize.toString(),
      proxyProfile
    }

    orders.push(primaryOrder, hedgeOrder)
    return orders
  }

  /**
   * 执行对冲订单
   */
  private async executeHedgeOrders(orders: HedgeOrder[]): Promise<HedgeOrder[]> {
    const results: HedgeOrder[] = []

    for (const order of orders) {
      try {
        // 构建交易信号
        const signal: TradingSignal = {
          symbol: 'BTC', // 简化，实际应该从订单获取
          action: order.side,
          side: order.side,
          amount: order.amount,
          confidence: 1.0,
          reason: 'Delta hedge execution',
          targetAccount: order.accountId
        }

        // 执行订单
        const result = await this.orderExecutor.executeOrder(signal)
        
        // 更新订单结果
        order.exchangeOrderId = result.orderId
        order.filledSize = result.filledSize
        order.avgPrice = result.avgPrice
        order.fees = result.fees
        order.result = result.success ? 'filled' : 'failed'
        order.error = result.error

        logger.info(`对冲订单执行结果`, {
          accountId: order.accountId,
          side: order.side,
          amount: order.amount,
          success: result.success,
          orderId: result.orderId
        })

      } catch (error: any) {
        order.result = 'failed'
        order.error = error.message
        logger.error(`对冲订单执行失败`, {
          accountId: order.accountId,
          side: order.side,
          amount: order.amount,
          error: error.message
        })
      }

      results.push(order)
    }

    return results
  }

  /**
   * 计算最终 Delta
   */
  private async calculateFinalDelta(
    primaryAccountId: string,
    hedgeAccountId: string,
    executionResults: HedgeOrder[]
  ): Promise<number> {
    try {
      // 获取账户状态
      const primaryState = this.accountManager.getAccountState(primaryAccountId)
      const hedgeState = this.accountManager.getAccountState(hedgeAccountId)

      if (!primaryState || !hedgeState) {
        throw new Error('Cannot get account states for delta calculation')
      }

      // 计算 Delta（简化版本）
      const primaryDelta = primaryState.netPosition || 0
      const hedgeDelta = hedgeState.netPosition || 0
      const totalDelta = primaryDelta + hedgeDelta

      return totalDelta

    } catch (error: any) {
      logger.warn(`计算最终 Delta 失败: ${error.message}`)
      return 0 // 返回 0 作为默认值
    }
  }

  /**
   * 生成执行警报
   */
  private generateExecutionAlerts(execution: HedgeExecution, orders: HedgeOrder[]): any[] {
    const alerts: any[] = []

    // 检查执行结果
    if (execution.result === 'fail') {
      alerts.push({
        type: 'hedge-failed',
        message: 'Hedge execution failed',
        severity: 'CRITICAL'
      })
    } else if (execution.result === 'partial') {
      alerts.push({
        type: 'hedge-partial',
        message: 'Hedge execution partially completed',
        severity: 'WARN'
      })
    }

    // 检查订单执行情况
    const failedOrders = orders.filter(o => o.result === 'failed')
    if (failedOrders.length > 0) {
      alerts.push({
        type: 'order-failed',
        message: `${failedOrders.length} orders failed to execute`,
        severity: 'WARN'
      })
    }

    // 检查执行时间
    if (execution.durationMs > 30000) { // 超过 30 秒
      alerts.push({
        type: 'slow-execution',
        message: `Hedge execution took ${execution.durationMs}ms`,
        severity: 'INFO'
      })
    }

    return alerts
  }

  /**
   * 验证对冲请求
   */
  private validateHedgeRequest(request: HedgeExecutionRequest): { isValid: boolean; errors: string[] } {
    const errors: string[] = []

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

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

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

    if (request.deltaBefore === undefined) {
      errors.push('deltaBefore is required')
    }

    if (request.targetDelta === undefined) {
      errors.push('targetDelta is required')
    }

    if (!['utilization', 'delta', 'failover', 'manual'].includes(request.triggerReason)) {
      errors.push('triggerReason must be one of: utilization, delta, failover, manual')
    }

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

  /**
   * 获取对冲执行历史
   */
  getHedgeHistory(accountId?: string): HedgeExecution[] {
    const executions = this.hedgeManager.getAllExecutions()
    
    if (accountId) {
      return this.hedgeManager.getExecutionsByAccount(accountId)
    }
    
    return executions
  }

  /**
   * 获取对冲统计
   */
  getHedgeStats(): {
    total: number
    successful: number
    partial: number
    failed: number
    successRate: number
    averageDuration: number
  } {
    return this.hedgeManager.getExecutionStats()
  }
}
