/**
 * 内部凭据管理服务 - 专注于Pacifica平台
 * 供项目内部其他模块调用，不提供HTTP API
 */

import { EventEmitter } from 'events'
import { PlatformAccount, SignatureResult, PacificaSignData, ErrorCode } from '../shared/credential-types'
import { createApiError, formatTimestamp, PerformanceTimer } from '../shared/credential-utils'
import { CredentialConfigLoader } from '../core/config-loader'
import { PacificaSignatureAdapter } from '../core/signature-adapters/pacifica'

/**
 * 内部凭据管理服务
 */
export class InternalCredentialService extends EventEmitter {
  private _configLoader: CredentialConfigLoader
  private _pacificaAdapter: PacificaSignatureAdapter
  private _initialized: boolean = false

  constructor(configPath?: string) {
    super()

    this._configLoader = new CredentialConfigLoader(configPath)
    this._pacificaAdapter = new PacificaSignatureAdapter()

    // 转发配置加载器事件
    this._configLoader.on('config:loaded', event => this.emit('config:loaded', event))
    this._configLoader.on('config:reloaded', event => this.emit('config:reloaded', event))
    this._configLoader.on('config:error', event => this.emit('config:error', event))

    console.log(`🔐 [CredentialService] 内部凭据服务初始化 (Pacifica专用)`)
  }

  /**
   * 初始化服务
   */
  async initialize(): Promise<void> {
    if (this._initialized) {
      return
    }

    try {
      await this._configLoader.loadConfig()
      this._configLoader.watchConfig()
      this._initialized = true

      console.log(`✅ [CredentialService] 内部凭据服务初始化完成`)
      this.emit('service:initialized', {
        timestamp: formatTimestamp(),
        accountCount: this._configLoader.accounts.size,
      })
    } catch (error) {
      console.error(`❌ [CredentialService] 初始化失败:`, error)
      throw error
    }
  }

  /**
   * 执行Pacifica签名 (主要方法)
   */
  async signPacifica(accountId: string, data: PacificaSignData): Promise<SignatureResult> {
    const timer = new PerformanceTimer()

    try {
      if (!this._initialized) {
        await this.initialize()
      }

      // 获取账户信息
      const account = this.getAccount('pacifica', accountId)
      if (!account) {
        throw createApiError(ErrorCode.ACCOUNT_NOT_FOUND, {
          platformId: 'pacifica',
          accountId,
        })
      }

      // 检查账户状态
      if (account.status !== 'active') {
        throw createApiError(ErrorCode.ACCOUNT_INACTIVE, {
          platformId: 'pacifica',
          accountId,
          status: account.status,
        })
      }

      // 执行签名
      const result = await this._pacificaAdapter.sign(data, {
        privateKey: account.credentials.privateKey!,
      })

      const elapsedMs = timer.elapsed()

      // 更新使用统计
      this._updateAccountUsage(account, true, elapsedMs)

      console.log(`✅ [CredentialService] Pacifica签名完成: ${accountId} (${elapsedMs.toFixed(1)}ms)`)

      this.emit('signature:success', {
        platformId: 'pacifica',
        accountId,
        algorithm: result.algorithm,
        executionTimeMs: elapsedMs,
        timestamp: formatTimestamp(),
      })

      return result
    } catch (error) {
      const elapsedMs = timer.elapsed()
      console.error(`❌ [CredentialService] Pacifica签名失败: ${accountId} (${elapsedMs.toFixed(1)}ms)`, error)

      this.emit('signature:error', {
        platformId: 'pacifica',
        accountId,
        error: error instanceof Error ? error.message : String(error),
        executionTimeMs: elapsedMs,
        timestamp: formatTimestamp(),
      })

      throw error
    }
  }

  /**
   * 批量Pacifica签名
   */
  async signPacificaBatch(
    requests: Array<{
      accountId: string
      data: PacificaSignData
      requestId?: string
    }>,
  ): Promise<
    Array<{
      accountId: string
      requestId?: string
      success: boolean
      result?: SignatureResult
      error?: string
    }>
  > {
    const timer = new PerformanceTimer()
    const results = []

    console.log(`🔄 [CredentialService] 开始批量Pacifica签名: ${requests.length}个请求`)

    for (const request of requests) {
      try {
        const result = await this.signPacifica(request.accountId, request.data)
        results.push({
          accountId: request.accountId,
          requestId: request.requestId,
          success: true,
          result,
        })
      } catch (error) {
        results.push({
          accountId: request.accountId,
          requestId: request.requestId,
          success: false,
          error: error instanceof Error ? error.message : String(error),
        })
      }
    }

    const elapsedMs = timer.elapsed()
    const successful = results.filter(r => r.success).length

    console.log(`✅ [CredentialService] 批量签名完成: ${successful}/${requests.length} (${elapsedMs.toFixed(1)}ms)`)

    return results
  }

  /**
   * 获取账户信息
   */
  getAccount(platformId: string, accountId: string): PlatformAccount | null {
    return this._configLoader.getAccount(platformId, accountId)
  }

  /**
   * 获取所有Pacifica账户
   */
  getPacificaAccounts(): PlatformAccount[] {
    return this._configLoader.getAccountsByPlatform('pacifica')
  }

  /**
   * 重新加载配置
   */
  async reloadConfig(): Promise<void> {
    console.log(`🔄 [CredentialService] 重新加载配置`)
    await this._configLoader.reloadConfig()
  }

  /**
   * 获取服务状态
   */
  getStatus() {
    const stats = this._configLoader.getStats()
    const pacificaAccounts = this.getPacificaAccounts()

    return {
      initialized: this._initialized,
      configPath: stats.configPath,
      lastLoaded: stats.lastLoaded,
      totalAccounts: stats.totalAccounts,
      pacificaAccounts: pacificaAccounts.length,
      accountStats: pacificaAccounts.map(account => ({
        accountId: account.accountId,
        alias: account.alias,
        environment: account.environment,
        status: account.status,
        totalSigns: account.usage.totalSigns,
        errorCount: account.usage.errorCount,
        lastUsed: account.usage.lastSignAt,
      })),
    }
  }

  /**
   * 检查账户是否存在
   */
  hasAccount(accountId: string): boolean {
    return this.getAccount('pacifica', accountId) !== null
  }

  /**
   * 获取账户公钥
   */
  getAccountPublicKey(accountId: string): string | null {
    const account = this.getAccount('pacifica', accountId)
    if (!account || !account.credentials.privateKey) {
      return null
    }

    try {
      return this._pacificaAdapter.derivePublicKey(account.credentials.privateKey)
    } catch (error) {
      console.error(`❌ [CredentialService] 获取公钥失败: ${accountId}`, error)
      return null
    }
  }

  /**
   * 私有方法：更新账户使用统计
   */
  private _updateAccountUsage(account: PlatformAccount, success: boolean, executionTimeMs: number): void {
    try {
      if (success) {
        account.usage.totalSigns++
        account.usage.lastSignAt = new Date()
      } else {
        account.usage.errorCount++
      }
      account.updatedAt = new Date()
    } catch (error) {
      console.error(`❌ [CredentialService] 更新账户统计失败:`, error)
    }
  }

  /**
   * 优雅关闭
   */
  async shutdown(): Promise<void> {
    console.log(`🛑 [CredentialService] 关闭内部凭据服务`)
    await this._configLoader.shutdown()
    this.removeAllListeners()
    this._initialized = false
  }
}

// 创建单例实例，供全局使用
let globalCredentialService: InternalCredentialService | null = null

/**
 * 获取全局凭据服务实例
 */
export function getCredentialService(configPath?: string): InternalCredentialService {
  if (!globalCredentialService) {
    globalCredentialService = new InternalCredentialService(configPath)
  }
  return globalCredentialService
}

/**
 * 便捷的Pacifica签名函数
 */
export async function signPacifica(accountId: string, data: PacificaSignData): Promise<SignatureResult> {
  const service = getCredentialService()
  return await service.signPacifica(accountId, data)
}

/**
 * 便捷的批量Pacifica签名函数
 */
export async function signPacificaBatch(
  requests: Array<{
    accountId: string
    data: PacificaSignData
    requestId?: string
  }>,
): Promise<
  Array<{
    accountId: string
    requestId?: string
    success: boolean
    result?: SignatureResult
    error?: string
  }>
> {
  const service = getCredentialService()
  return await service.signPacificaBatch(requests)
}

/**
 * 检查Pacifica账户是否存在
 */
export function hasPacificaAccount(accountId: string): boolean {
  const service = getCredentialService()
  return service.hasAccount(accountId)
}

/**
 * 获取Pacifica账户公钥
 */
export function getPacificaPublicKey(accountId: string): string | null {
  const service = getCredentialService()
  return service.getAccountPublicKey(accountId)
}
