/**
 * 多平台账户凭据管理系统 - 通用工具函数
 */

import { VALIDATION_RULES, ERROR_MESSAGES } from './credential-constants'
import { ErrorCode, PlatformType, ApiError } from './credential-types'

/**
 * 生成账户唯一键
 */
export function generateAccountKey(platformId: PlatformType, accountId: string): string {
  return `${platformId}:${accountId}`
}

/**
 * 解析账户唯一键
 */
export function parseAccountKey(accountKey: string): { platformId: PlatformType; accountId: string } | null {
  const parts = accountKey.split(':')
  if (parts.length !== 2) {
    return null
  }

  const [platformId, accountId] = parts
  if (!isValidPlatform(platformId)) {
    return null
  }

  return { platformId: platformId as PlatformType, accountId }
}

/**
 * 验证平台类型
 */
export function isValidPlatform(platform: string): platform is PlatformType {
  return ['pacifica', 'aster', 'binance', 'okx'].includes(platform)
}

/**
 * 验证账户ID格式
 */
export function validateAccountId(accountId: string): boolean {
  const { MIN_LENGTH, MAX_LENGTH, PATTERN } = VALIDATION_RULES.ACCOUNT_ID

  return accountId.length >= MIN_LENGTH && accountId.length <= MAX_LENGTH && PATTERN.test(accountId)
}

/**
 * 验证Pacifica私钥格式
 */
export function validatePacificaPrivateKey(privateKey: string): boolean {
  const { LENGTH, PATTERN } = VALIDATION_RULES.PACIFICA_PRIVATE_KEY

  return privateKey.length === LENGTH && PATTERN.test(privateKey)
}

/**
 * 验证以太坊私钥格式
 */
export function validateEthPrivateKey(privateKey: string): boolean {
  const { LENGTH, PATTERN } = VALIDATION_RULES.ETH_PRIVATE_KEY

  return privateKey.length === LENGTH && PATTERN.test(privateKey)
}

/**
 * 验证API Key格式
 */
export function validateApiKey(apiKey: string): boolean {
  const { MIN_LENGTH, MAX_LENGTH } = VALIDATION_RULES.API_KEY

  return apiKey.length >= MIN_LENGTH && apiKey.length <= MAX_LENGTH
}

/**
 * 创建API错误对象
 */
export function createApiError(code: ErrorCode, details?: Record<string, any>): ApiError {
  return {
    code,
    message: ERROR_MESSAGES[code],
    details,
  }
}

/**
 * 安全地脱敏私钥信息（用于日志记录）
 */
export function sanitizePrivateKey(privateKey: string): string {
  if (privateKey.length <= 8) {
    return '***'
  }
  return `${privateKey.substring(0, 4)}***${privateKey.substring(privateKey.length - 4)}`
}

/**
 * 安全地脱敏API Key信息（用于日志记录）
 */
export function sanitizeApiKey(apiKey: string): string {
  if (apiKey.length <= 8) {
    return '***'
  }
  return `${apiKey.substring(0, 4)}***${apiKey.substring(apiKey.length - 4)}`
}

/**
 * 深度克隆对象（避免敏感数据引用）
 */
export function deepClone<T>(obj: T): T {
  if (obj === null || typeof obj !== 'object') {
    return obj
  }

  if (obj instanceof Date) {
    return new Date(obj.getTime()) as unknown as T
  }

  if (obj instanceof Array) {
    return obj.map(item => deepClone(item)) as unknown as T
  }

  const clonedObj = {} as T
  for (const key in obj) {
    if (obj.hasOwnProperty(key)) {
      clonedObj[key] = deepClone(obj[key])
    }
  }

  return clonedObj
}

/**
 * 安全地清理敏感数据（将Buffer置零）
 */
export function secureClear(buffer: Buffer): void {
  if (buffer && Buffer.isBuffer(buffer)) {
    buffer.fill(0)
  }
}

/**
 * 延迟执行（用于防抖）
 */
export function debounce<T extends (...args: any[]) => any>(func: T, waitMs: number): (...args: Parameters<T>) => void {
  let timeoutId: NodeJS.Timeout

  return (...args: Parameters<T>) => {
    clearTimeout(timeoutId)
    timeoutId = setTimeout(() => func(...args), waitMs)
  }
}

/**
 * 性能计时器
 */
export class PerformanceTimer {
  private startTime: number

  constructor() {
    this.startTime = performance.now()
  }

  /**
   * 获取经过的毫秒数
   */
  elapsed(): number {
    return performance.now() - this.startTime
  }

  /**
   * 重置计时器
   */
  reset(): void {
    this.startTime = performance.now()
  }
}

/**
 * 格式化时间戳为ISO字符串
 */
export function formatTimestamp(date: Date = new Date()): string {
  return date.toISOString()
}

/**
 * 判断是否为生产环境
 */
export function isProduction(): boolean {
  return process.env.NODE_ENV === 'production'
}

/**
 * 获取环境变量值（带默认值）
 */
export function getEnvVar(key: string, defaultValue: string = ''): string {
  return process.env[key] || defaultValue
}

/**
 * 将错误对象转换为可序列化的对象
 */
export function serializeError(error: Error): Record<string, any> {
  return {
    name: error.name,
    message: error.message,
    stack: error.stack,
    timestamp: formatTimestamp(),
  }
}

/**
 * 验证JSON格式
 */
export function isValidJson(str: string): boolean {
  try {
    JSON.parse(str)
    return true
  } catch {
    return false
  }
}

/**
 * Base58编码验证
 */
export function isValidBase58(str: string): boolean {
  const base58Alphabet = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
  return str.split('').every(char => base58Alphabet.includes(char))
}

/**
 * 十六进制字符串验证
 */
export function isValidHex(str: string): boolean {
  return /^0x[a-fA-F0-9]+$/.test(str)
}
