/**
 * 配置管理器实现 - 配置文件加载和热重载
 * 专注于Pacifica平台的凭据管理
 */

import fs from 'fs'
import path from 'path'
import { EventEmitter } from 'events'
import { ConfigManager, PlatformAccount, PlatformType, EnvironmentType, ErrorCode } from '../shared/credential-types'
import { DEFAULT_CONFIG, VALIDATION_RULES } from '../shared/credential-constants'
import {
  generateAccountKey,
  validateAccountId,
  validatePacificaPrivateKey,
  debounce,
  createApiError,
  formatTimestamp,
  PerformanceTimer,
} from '../shared/credential-utils'

/**
 * 配置文件格式接口
 */
interface ConfigFile {
  pacifica?: Array<{
    accountId: string
    alias?: string
    privateKey: string
    environment?: EnvironmentType
  }>
  // 预留其他平台配置结构
  aster?: Array<any>
  binance?: Array<any>
  okx?: Array<any>
}

/**
 * 配置加载器实现
 */
export class CredentialConfigLoader extends EventEmitter implements ConfigManager {
  private _configPath: string
  private _lastLoaded: Date
  private _accounts: Map<string, PlatformAccount>
  private _watcherInitialized: boolean = false
  private _reloadDebounced: () => void

  constructor(configPath?: string) {
    super()
    this._configPath = path.resolve(configPath || DEFAULT_CONFIG.DEFAULT_CONFIG_PATH)
    this._lastLoaded = new Date(0) // 初始化为最早时间
    this._accounts = new Map()

    // 创建防抖的重载函数
    this._reloadDebounced = debounce(() => this._performReload(), DEFAULT_CONFIG.WATCH_DEBOUNCE_MS)
  }

  // ConfigManager接口实现
  get configPath(): string {
    return this._configPath
  }

  get lastLoaded(): Date {
    return this._lastLoaded
  }

  get accounts(): Map<string, PlatformAccount> {
    return new Map(this._accounts) // 返回副本
  }

  /**
   * 加载配置文件
   */
  async loadConfig(): Promise<void> {
    const timer = new PerformanceTimer()

    try {
      // 检查文件存在性
      if (!fs.existsSync(this._configPath)) {
        throw createApiError(ErrorCode.CONFIG_LOAD_FAILED, {
          reason: 'Config file not found',
          path: this._configPath,
        })
      }

      // 读取和解析配置文件
      const configContent = fs.readFileSync(this._configPath, 'utf-8')
      const configData: ConfigFile = JSON.parse(configContent)

      // 验证和加载账户
      const newAccounts = new Map<string, PlatformAccount>()

      if (configData.pacifica) {
        await this._loadPacificaAccounts(configData.pacifica, newAccounts)
      }

      // 原子性更新账户数据
      this._accounts = newAccounts
      this._lastLoaded = new Date()

      const elapsedMs = timer.elapsed()

      this.emit('config:loaded', {
        path: this._configPath,
        accountCount: this._accounts.size,
        loadTimeMs: elapsedMs,
        timestamp: formatTimestamp(),
      })

      console.log(`✅ [ConfigLoader] 配置加载成功: ${this._accounts.size}个账户, 耗时${elapsedMs.toFixed(1)}ms`)
    } catch (error) {
      const apiError =
        error instanceof Error
          ? createApiError(ErrorCode.CONFIG_LOAD_FAILED, {
              reason: error.message,
              path: this._configPath,
              timestamp: formatTimestamp(),
            })
          : error

      this.emit('config:error', apiError)
      throw apiError
    }
  }

  /**
   * 重新加载配置文件
   */
  async reloadConfig(): Promise<void> {
    console.log(`🔄 [ConfigLoader] 开始重新加载配置: ${this._configPath}`)
    await this.loadConfig()
  }

  /**
   * 监控配置文件变化
   */
  watchConfig(): void {
    if (this._watcherInitialized) {
      console.log(`⚠️ [ConfigLoader] 文件监控已初始化`)
      return
    }

    try {
      fs.watch(this._configPath, (eventType, filename) => {
        if (eventType === 'change') {
          console.log(`📝 [ConfigLoader] 检测到配置文件变化: ${filename}`)
          this._reloadDebounced()
        }
      })

      this._watcherInitialized = true
      console.log(`👁️ [ConfigLoader] 开始监控配置文件: ${this._configPath}`)
    } catch (error) {
      console.error(`❌ [ConfigLoader] 文件监控初始化失败:`, error)
      this.emit('config:watch_error', error)
    }
  }

  /**
   * 获取指定账户
   */
  getAccount(platformId: string, accountId: string): PlatformAccount | null {
    const key = generateAccountKey(platformId as PlatformType, accountId)
    return this._accounts.get(key) || null
  }

  /**
   * 获取指定平台的所有账户
   */
  getAccountsByPlatform(platformId: string): PlatformAccount[] {
    const accounts: PlatformAccount[] = []

    for (const [key, account] of this._accounts) {
      if (account.platformId === platformId) {
        accounts.push(account)
      }
    }

    return accounts
  }

  /**
   * 私有方法：加载Pacifica账户配置
   */
  private async _loadPacificaAccounts(
    pacificaConfigs: ConfigFile['pacifica'],
    targetMap: Map<string, PlatformAccount>,
  ): Promise<void> {
    if (!pacificaConfigs || !Array.isArray(pacificaConfigs)) {
      return
    }

    for (const config of pacificaConfigs) {
      await this._validateAndLoadPacificaAccount(config, targetMap)
    }
  }

  /**
   * 私有方法：验证并加载单个Pacifica账户
   */
  private async _validateAndLoadPacificaAccount(
    config: ConfigFile['pacifica'][0],
    targetMap: Map<string, PlatformAccount>,
  ): Promise<void> {
    // 验证必需字段
    if (!config.accountId || !config.privateKey) {
      throw new Error(`Pacifica账户配置缺少必需字段: accountId或privateKey`)
    }

    // 验证账户ID格式
    if (!validateAccountId(config.accountId)) {
      throw new Error(`无效的Pacifica账户ID格式: ${config.accountId}`)
    }

    // 验证私钥格式
    if (!validatePacificaPrivateKey(config.privateKey)) {
      throw new Error(`无效的Pacifica私钥格式: ${config.accountId}`)
    }

    // 检查重复账户
    const accountKey = generateAccountKey('pacifica', config.accountId)
    if (targetMap.has(accountKey)) {
      throw new Error(`重复的Pacifica账户ID: ${config.accountId}`)
    }

    // 创建账户对象
    const account: PlatformAccount = {
      accountId: config.accountId,
      platformId: 'pacifica',
      alias: config.alias || `Pacifica账户-${config.accountId}`,
      credentials: {
        privateKey: config.privateKey,
      },
      status: 'active',
      environment: config.environment || 'development',
      usage: {
        totalSigns: 0,
        errorCount: 0,
      },
      createdAt: new Date(),
      updatedAt: new Date(),
    }

    targetMap.set(accountKey, account)
    console.log(`✅ [ConfigLoader] 加载Pacifica账户: ${config.accountId} (${account.environment})`)
  }

  /**
   * 私有方法：执行配置重载
   */
  private async _performReload(): Promise<void> {
    try {
      const oldAccountCount = this._accounts.size
      await this.reloadConfig()
      const newAccountCount = this._accounts.size

      this.emit('config:reloaded', {
        path: this._configPath,
        oldAccountCount,
        newAccountCount,
        timestamp: formatTimestamp(),
      })
    } catch (error) {
      console.error(`❌ [ConfigLoader] 配置重载失败:`, error)
      this.emit('config:reload_error', error)
    }
  }

  /**
   * 获取配置统计信息
   */
  getStats() {
    const platformStats: Record<string, number> = {}
    const environmentStats: Record<string, number> = {}

    for (const account of this._accounts.values()) {
      // 平台统计
      platformStats[account.platformId] = (platformStats[account.platformId] || 0) + 1

      // 环境统计
      environmentStats[account.environment] = (environmentStats[account.environment] || 0) + 1
    }

    return {
      totalAccounts: this._accounts.size,
      platformStats,
      environmentStats,
      lastLoaded: this._lastLoaded,
      configPath: this._configPath,
      isWatching: this._watcherInitialized,
    }
  }

  /**
   * 优雅关闭
   */
  async shutdown(): Promise<void> {
    this.removeAllListeners()
    this._accounts.clear()
    console.log(`🛑 [ConfigLoader] 已关闭`)
  }
}
