import { TradingSignal } from '../types.js'
import { AccountManager } from '../account/AccountManager.js'
import { RiskManager } from '../risk/RiskManager.js'
import { SamePlatformHedgingManager } from '../../core/hedging/SamePlatformHedgingManager.js'
import { logger } from '../../utils/logger.js'
import { globalPriceManager } from '../price/PriceManager.js'

/**
 * 交易信号生成器 - 从TradingEngine中分离出来的信号生成逻辑
 */
export class SignalGenerator {
  constructor(
    private accountManager: AccountManager,
    private riskManager: RiskManager,
    private hedgeManager: SamePlatformHedgingManager | null = null,
  ) {}

  /**
   * 生成主要交易信号
   */
  async generateTradingSignals(): Promise<TradingSignal[]> {
    const signals: TradingSignal[] = []

    try {
      // 1. 余额检查信号
      const balanceSignal = this.generateBalanceSignal()
      if (balanceSignal) {
        signals.push(balanceSignal)
      }

      // 2. 平仓信号
      const closeSignal = await this.generateCloseSignal()
      if (closeSignal) {
        signals.push(closeSignal)
      }

      // 3. 智能对冲信号
      const hedgeSignal = await this.generateSmartHedgeSignal()
      if (hedgeSignal) {
        signals.push(hedgeSignal)
      }

      // 4. 批量交易信号
      const volumeSignals = await this.generateVolumeBoostSignals()
      signals.push(...volumeSignals)

      logger.debug(`生成了 ${signals.length} 个交易信号`)
      return signals
    } catch (error) {
      logger.error('生成交易信号失败', { error })
      return []
    }
  }

  /**
   * 生成量化信号
   */
  async generateVolumeBoostSignals(): Promise<TradingSignal[]> {
    const signals: TradingSignal[] = []

    try {
      const accounts = this.accountManager.getAccounts()
      if (accounts.length < 2) return signals

      // 为前两个账户生成批量交易信号
      const mainAccount = accounts[0]
      const hedgeAccount = accounts[1]

      // 检查账户余额是否足够
      const mainBalance = await this.accountManager.getBalance(mainAccount.id)
      const hedgeBalance = await this.accountManager.getBalance(hedgeAccount.id)

      if (!mainBalance?.USDT || !hedgeBalance?.USDT) return signals

      const mainUSDT = parseFloat(mainBalance.USDT.free)
      const hedgeUSDT = parseFloat(hedgeBalance.USDT.free)

      if (mainUSDT > 50 && hedgeUSDT > 50) {
        // 为主账户生成买入信号
        signals.push({
          type: 'volume_boost',
          symbol: 'BTC-USD',
          side: 'buy',
          accountId: mainAccount.id,
          amount: '0.0005', // 小批量
          priority: 'medium',
          reason: '批量买入 - 增加交易量',
          strategy: 'volume_boost',
          timestamp: Date.now(),
        })

        // 为对冲账户生成卖出信号
        signals.push({
          type: 'volume_boost',
          symbol: 'BTC-USD',
          side: 'sell',
          accountId: hedgeAccount.id,
          amount: '0.0005', // 小批量
          priority: 'medium',
          reason: '批量卖出 - 对冲交易',
          strategy: 'volume_boost',
          timestamp: Date.now(),
        })
      }

      return signals
    } catch (error) {
      logger.error('生成批量交易信号失败', { error })
      return signals
    }
  }

  /**
   * 检查账户余额并生成相关信号
   */
  private generateBalanceSignal(): TradingSignal | null {
    try {
      const accounts = this.accountManager.getAccounts()
      if (accounts.length === 0) return null

      // 检查账户余额
      for (const account of accounts) {
        const accountData = this.accountManager.getAccountData(account.id)
        if (!accountData || !accountData.balances) continue

        const usdtBalance = accountData.balances.USDT
        if (usdtBalance && parseFloat(usdtBalance.free) < 10) {
          return {
            type: 'balance',
            symbol: 'BTC-USD',
            side: 'hold',
            accountId: account.id,
            amount: '0',
            priority: 'high',
            reason: `账户余额不足: ${usdtBalance.free} USDT`,
            strategy: 'balance_check',
            timestamp: Date.now(),
          }
        }
      }

      return null
    } catch (error) {
      logger.error('生成余额信号失败', { error })
      return null
    }
  }

  /**
   * 生成平仓信号
   */
  private async generateCloseSignal(): Promise<TradingSignal | null> {
    try {
      const accounts = this.accountManager.getAccounts()
      if (accounts.length === 0) return null

      // 检查是否需要平仓
      const shouldClose = this.shouldCloseExistingPositions()
      if (!shouldClose) return null

      // 选择第一个有仓位的账户
      for (const account of accounts) {
        const accountData = this.accountManager.getAccountData(account.id)
        if (!accountData || !accountData.positions) continue

        const positions = Object.values(accountData.positions)
        const activePosition = positions.find(pos => Math.abs(parseFloat(pos.size)) > 0.0001)

        if (activePosition) {
          return {
            type: 'close',
            symbol: activePosition.symbol,
            side: parseFloat(activePosition.size) > 0 ? 'sell' : 'buy',
            accountId: account.id,
            amount: Math.abs(parseFloat(activePosition.size)).toString(),
            priority: 'high',
            reason: '风险控制 - 平仓现有仓位',
            strategy: 'risk_control',
            timestamp: Date.now(),
          }
        }
      }

      return null
    } catch (error) {
      logger.error('生成平仓信号失败', { error })
      return null
    }
  }

  /**
   * 生成智能对冲信号
   */
  private async generateSmartHedgeSignal(): Promise<TradingSignal | null> {
    try {
      if (!this.hedgeManager) return null

      // 检查对冲需求
      const hedgePairs = this.hedgeManager.getHedgePairs()
      if (hedgePairs.length === 0) return null

      // 简化的对冲逻辑 - 检查第一个对冲对
      const firstPair = hedgePairs[0]
      const netExposure = await this.hedgeManager.calculateNetExposure(firstPair.id)

      if (Math.abs(netExposure) > 0.001) {
        const hedgeAccount = netExposure > 0 ? firstPair.hedgeAccountId : firstPair.mainAccountId
        const hedgeSide = netExposure > 0 ? 'sell' : 'buy'
        const hedgeAmount = Math.abs(netExposure).toString()

        return {
          type: 'hedge',
          symbol: firstPair.symbol,
          side: hedgeSide,
          accountId: hedgeAccount,
          amount: hedgeAmount,
          priority: 'high',
          reason: `对冲净敞口: ${netExposure.toFixed(6)} BTC`,
          strategy: 'smart_hedge',
          timestamp: Date.now(),
        }
      }

      return null
    } catch (error) {
      logger.error('生成对冲信号失败', { error })
      return null
    }
  }

  /**
   * 检查是否应该平仓
   */
  private shouldCloseExistingPositions(): boolean {
    try {
      const avgUtilization = this.calculateAverageUtilizationRate()

      // 当平均利用率过高时平仓
      if (avgUtilization > 0.8) {
        logger.info(`平均利用率过高 ${(avgUtilization * 100).toFixed(2)}%, 建议平仓`)
        return true
      }

      // 其他风险条件检查
      const riskProfile = this.riskManager.assessCurrentRisk()
      if (riskProfile.level === 'HIGH') {
        logger.info('风险等级过高，建议平仓')
        return true
      }

      return false
    } catch (error) {
      logger.error('检查平仓条件失败', { error })
      return false
    }
  }

  /**
   * 计算平均利用率
   */
  private calculateAverageUtilizationRate(): number {
    try {
      const accounts = this.accountManager.getAccounts()
      if (accounts.length === 0) return 0

      let totalUtilization = 0
      let validAccounts = 0

      for (const account of accounts) {
        const accountData = this.accountManager.getAccountData(account.id)
        if (!accountData || !accountData.balances || !accountData.positions) continue

        const usdtBalance = accountData.balances.USDT
        if (!usdtBalance) continue

        const totalBalance = parseFloat(usdtBalance.total)
        const freeBalance = parseFloat(usdtBalance.free)

        if (totalBalance > 0) {
          const utilizationRate = (totalBalance - freeBalance) / totalBalance
          totalUtilization += utilizationRate
          validAccounts++
        }
      }

      return validAccounts > 0 ? totalUtilization / validAccounts : 0
    } catch (error) {
      logger.error('计算平均利用率失败', { error })
      return 0
    }
  }
}