/**
 * 策略模块管理服务
 * 集成现有的交易引擎和策略系统
 */
import { 
  StrategyModuleManager,
  StrategyModule,
  StrategySignal,
  StrategyExecutionResult,
  StrategyConfigTemplate
} from '../models/StrategyModule.js'
import { AccountAllocationManager } from '../models/AccountAllocation.js'
import { OrderIntentManager } from '../models/OrderIntent.js'
import { TradingSignal } from '../modules/types.js'
import { logger } from '../utils/logger.js'

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

export class StrategyModuleService {
  private moduleManager: StrategyModuleManager
  private allocationManager: AccountAllocationManager
  private orderIntentManager: OrderIntentManager
  private strategyExecutor: StrategyExecutor

  constructor(
    moduleManager: StrategyModuleManager,
    allocationManager: AccountAllocationManager,
    orderIntentManager: OrderIntentManager,
    strategyExecutor: StrategyExecutor
  ) {
    this.moduleManager = moduleManager
    this.allocationManager = allocationManager
    this.orderIntentManager = orderIntentManager
    this.strategyExecutor = strategyExecutor
  }

  /**
   * 创建策略模块
   */
  async createModule(config: {
    name: string
    type: StrategyModule['type']
    configSchema: Record<string, any>
    defaultConfig?: Record<string, any>
  }): Promise<StrategyModule> {
    logger.info(`创建策略模块: ${config.name} (${config.type})`)

    const module: StrategyModule = {
      moduleId: `${config.type}-${Date.now()}`,
      name: config.name,
      type: config.type,
      configSchema: config.configSchema,
      dryRunEnabled: true,
      maxConcurrentSignals: 3,
      profitAfterFeeTarget: 0.001, // 0.1% 默认目标
      requiresSandbox: true,
      status: 'enable',
      ...config.defaultConfig
    }

    // 验证模块配置
    const validation = this.moduleManager.validateModule(module)
    if (!validation.isValid) {
      throw new Error(`Invalid module configuration: ${validation.errors.join(', ')}`)
    }

    // 添加模块
    this.moduleManager.addModule(module)

    logger.info(`策略模块创建成功: ${module.moduleId}`)
    return module
  }

  /**
   * 从模板创建策略模块
   */
  async createModuleFromTemplate(templateId: string, customConfig?: Record<string, any>): Promise<StrategyModule | null> {
    logger.info(`从模板创建策略模块: ${templateId}`)

    const module = this.moduleManager.createModuleFromTemplate(templateId, customConfig)
    if (module) {
      logger.info(`从模板创建策略模块成功: ${module.moduleId}`)
    } else {
      logger.error(`从模板创建策略模块失败: ${templateId}`)
    }

    return module
  }

  /**
   * 生成策略信号
   */
  async generateSignal(moduleId: string, signalData: {
    symbol: string
    action: StrategySignal['action']
    side?: 'buy' | 'sell'
    amount: string
    price?: string
    confidence: number
    reason: string
  }): Promise<StrategySignal | null> {
    logger.debug(`生成策略信号: ${moduleId}`)

    // 检查模块是否可以执行
    const canExecute = this.moduleManager.canExecute(moduleId)
    if (!canExecute.canExecute) {
      logger.warn(`模块 ${moduleId} 无法执行: ${canExecute.reason}`)
      return null
    }

    // 创建策略信号
    const signal: StrategySignal = {
      signalId: `signal-${moduleId}-${Date.now()}`,
      moduleId,
      symbol: signalData.symbol,
      action: signalData.action,
      side: signalData.side,
      amount: signalData.amount,
      price: signalData.price,
      confidence: signalData.confidence,
      reason: signalData.reason,
      timestamp: new Date()
    }

    // 添加到管理器
    this.moduleManager.generateSignal(signal)

    logger.info(`策略信号生成成功: ${signal.signalId}`)
    return signal
  }

  /**
   * 执行策略信号
   */
  async executeSignal(signalId: string): Promise<StrategyExecutionResult | null> {
    const signal = this.moduleManager.getSignal(signalId)
    if (!signal) {
      logger.error(`策略信号不存在: ${signalId}`)
      return null
    }

    logger.info(`执行策略信号: ${signalId}`)

    try {
      // 获取账户分配
      const allocations = this.getAllocationManager().getAllAllocations()
        .filter(a => a.moduleId === signal.moduleId && a.sandboxMode === false)

      if (allocations.length === 0) {
        logger.warn(`没有可用的账户分配: ${signal.moduleId}`)
        return null
      }

      // 选择账户（简化：选择第一个可用账户）
      const allocation = allocations[0]

      // 构建交易信号
      const tradingSignal: TradingSignal = {
        symbol: signal.symbol,
        action: signal.action,
        side: signal.side,
        amount: signal.amount,
        price: signal.price,
        confidence: signal.confidence,
        reason: signal.reason,
        targetAccount: allocation.accountId
      }

      // 执行交易
      const executionResult = await this.strategyExecutor.executeSignal(tradingSignal)

      // 记录执行结果
      const result: StrategyExecutionResult = {
        signalId,
        moduleId: signal.moduleId,
        status: executionResult.success ? 'success' : 'failed',
        executedAmount: executionResult.filledSize || '0',
        avgPrice: executionResult.avgPrice,
        fees: executionResult.fees,
        profitAfterFee: executionResult.success ? this.calculateProfitAfterFee(executionResult) : '0',
        executionTime: new Date(),
        error: executionResult.error
      }

      this.moduleManager.recordExecution(result)

      logger.info(`策略信号执行完成: ${signalId}`, {
        status: result.status,
        executedAmount: result.executedAmount,
        profitAfterFee: result.profitAfterFee
      })

      return result

    } catch (error: any) {
      logger.error(`策略信号执行失败: ${signalId}, ${error.message}`)

      const result: StrategyExecutionResult = {
        signalId,
        moduleId: signal.moduleId,
        status: 'failed',
        executedAmount: '0',
        executionTime: new Date(),
        error: error.message
      }

      this.moduleManager.recordExecution(result)
      return result
    }
  }

  /**
   * 计算手续费后利润
   */
  private calculateProfitAfterFee(executionResult: any): string {
    // 简化计算：假设利润为执行金额的 0.1%
    const executedAmount = parseFloat(executionResult.filledSize || '0')
    const avgPrice = parseFloat(executionResult.avgPrice || '0')
    const fees = parseFloat(executionResult.fees || '0')
    
    const grossProfit = executedAmount * avgPrice * 0.001 // 0.1%
    const netProfit = grossProfit - fees
    
    return Math.max(0, netProfit).toString()
  }

  /**
   * 获取模块性能指标
   */
  getModulePerformance(moduleId: string, period: 'hour' | 'day' | 'week' | 'month' = 'day') {
    return this.moduleManager.calculatePerformanceMetrics(moduleId, period)
  }

  /**
   * 获取所有模块状态
   */
  getAllModulesStatus(): Array<{
    module: StrategyModule
    performance: any
    canExecute: boolean
    activeSignals: number
  }> {
    const modules = this.moduleManager.getAllModules()
    
    return modules.map(module => {
      const performance = this.moduleManager.calculatePerformanceMetrics(module.moduleId, 'day')
      const canExecute = this.moduleManager.canExecute(module.moduleId)
      const activeSignals = this.moduleManager.getModuleSignals(module.moduleId)
        .filter(signal => Date.now() - signal.timestamp.getTime() < 300000).length // 5分钟内

      return {
        module,
        performance,
        canExecute: canExecute.canExecute,
        activeSignals
      }
    })
  }

  /**
   * 批量执行模块信号
   */
  async batchExecuteSignals(moduleId: string, maxConcurrent: number = 3): Promise<StrategyExecutionResult[]> {
    const signals = this.moduleManager.getModuleSignals(moduleId)
      .filter(signal => Date.now() - signal.timestamp.getTime() < 60000) // 1分钟内的信号
      .slice(0, maxConcurrent)

    logger.info(`批量执行模块信号: ${moduleId}, 信号数量: ${signals.length}`)

    const results: StrategyExecutionResult[] = []
    
    for (const signal of signals) {
      const result = await this.executeSignal(signal.signalId)
      if (result) {
        results.push(result)
      }
    }

    return results
  }

  /**
   * 启用/禁用策略模块
   */
  setModuleStatus(moduleId: string, status: 'enable' | 'disable'): boolean {
    const success = this.moduleManager.setModuleStatus(moduleId, status)
    if (success) {
      logger.info(`策略模块状态更新: ${moduleId} -> ${status}`)
    } else {
      logger.error(`策略模块状态更新失败: ${moduleId}`)
    }
    return success
  }

  /**
   * 清理过期信号
   */
  cleanupExpiredSignals(maxAgeHours: number = 24): number {
    const modules = this.moduleManager.getAllModules()
    let cleanedCount = 0

    for (const module of modules) {
      const signals = this.moduleManager.getModuleSignals(module.moduleId)
      const cutoffTime = new Date(Date.now() - maxAgeHours * 60 * 60 * 1000)

      for (const signal of signals) {
        if (signal.timestamp < cutoffTime) {
          // 这里需要添加清理逻辑到 StrategyModuleManager
          cleanedCount++
        }
      }
    }

    if (cleanedCount > 0) {
      logger.info(`清理过期策略信号: ${cleanedCount} 个`)
    }

    return cleanedCount
  }

  /**
   * 获取策略模块管理器
   */
  getModuleManager(): StrategyModuleManager {
    return this.moduleManager
  }

  /**
   * 获取账户分配管理器
   */
  getAllocationManager(): AccountAllocationManager {
    return this.allocationManager
  }

  /**
   * 获取订单意图管理器
   */
  getOrderIntentManager(): OrderIntentManager {
    return this.orderIntentManager
  }
}
