/**
 * Credential Manager Module - Public API
 *
 * Main entry point for the multi-platform credential management system.
 * Provides unified interface for account management, configuration loading,
 * and signing operations across Pacifica, Aster, and Binance platforms.
 */

// Main classes
export { CredentialManager } from './CredentialManager'
export { ConfigLoader } from './ConfigLoader'
export { CredentialValidator } from './CredentialValidator'
export { PlatformDetector } from './PlatformDetector'

// Platform-specific signers
export { PacificaSigner } from './signers/PacificaSigner'

// Platform detectors
export { PacificaDetector, AsterDetector, BinanceDetector } from './PlatformDetector'

// Utility classes
export { PacificaKeyUtils, PacificaSignerMetrics } from './signers/PacificaSigner'

// Re-export all types from the types module
export * from '@/types/credential'

// Constants and defaults
export const CREDENTIAL_MANAGER_VERSION = '1.0.0'

export const DEFAULT_CONFIG_PATHS = [
  './credentials.json',
  './config/credentials.json',
  './credentials.yaml',
  './config/credentials.yaml',
]

export const SUPPORTED_PLATFORMS = ['PACIFICA', 'ASTER', 'BINANCE'] as const

export const SUPPORTED_SIGNATURE_TYPES = ['ed25519', 'eip191', 'hmac-sha256'] as const

// Performance constants
export const PERFORMANCE_REQUIREMENTS = {
  CONFIG_LOAD_TIME_MS: 100,
  SIGNING_TIME_MS: 50,
  MEMORY_LIMIT_MB: 50,
  MIN_SUPPORTED_ACCOUNTS: 50,
} as const

// Factory function for easy initialization
export function createCredentialManager(): CredentialManager {
  return new CredentialManager()
}

// Convenience function to create and load configuration
export async function createCredentialManagerWithConfig(configPath: string): Promise<{
  manager: CredentialManager
  loadResult: import('@/types/credential').LoadResult
}> {
  const manager = new CredentialManager()
  const loadResult = await manager.loadConfig(configPath)

  return {
    manager,
    loadResult,
  }
}

// Helper function to validate configuration file before loading
export async function validateConfigFile(configPath: string): Promise<{
  isValid: boolean
  errors: string[]
  warnings: string[]
  accountCount: number
  supportedPlatforms: string[]
}> {
  const configLoader = new ConfigLoader()
  const validator = new CredentialValidator()

  try {
    const loadResult = await configLoader.loadConfig(configPath)

    if (!loadResult.success) {
      return {
        isValid: false,
        errors: loadResult.errors || ['Configuration load failed'],
        warnings: [],
        accountCount: 0,
        supportedPlatforms: [],
      }
    }

    const validationReport = validator.generateValidationReport(
      loadResult.accounts.map(account => ({
        id: account.id,
        platform: account.platform,
        name: account.name,
        credentials: account.credentials,
        enabled: account.enabled,
        metadata: account.metadata,
      })),
    )

    const supportedPlatforms = Object.entries(validationReport.platformCounts)
      .filter(([_, count]) => count > 0)
      .map(([platform, _]) => platform)

    return {
      isValid: validationReport.isValid,
      errors: validationReport.globalErrors,
      warnings: validationReport.globalWarnings,
      accountCount: validationReport.validAccounts,
      supportedPlatforms,
    }
  } catch (error) {
    return {
      isValid: false,
      errors: [`Failed to validate configuration: ${error instanceof Error ? error.message : 'Unknown error'}`],
      warnings: [],
      accountCount: 0,
      supportedPlatforms: [],
    }
  }
}

// Helper function to generate configuration template
export function generateConfigTemplate(): import('@/types/credential').ConfigFile {
  const configLoader = new ConfigLoader()
  return configLoader.getConfigTemplate()
}

// Helper function to check system requirements
export function checkSystemRequirements(): {
  nodejs: { supported: boolean; version?: string }
  typescript: { supported: boolean }
  memory: { available: boolean; usage?: number }
  dependencies: {
    tweetnacl: boolean
  }
} {
  const requirements = {
    nodejs: { supported: false },
    typescript: { supported: false },
    memory: { available: false },
    dependencies: {
      tweetnacl: false,
    },
  }

  // Check Node.js version
  if (process.version) {
    const version = process.version
    const majorVersion = parseInt(version.slice(1).split('.')[0])
    requirements.nodejs = {
      supported: majorVersion >= 18,
      version,
    }
  }

  // Check TypeScript (basic check)
  try {
    require.resolve('typescript')
    requirements.typescript.supported = true
  } catch (error) {
    // TypeScript not available
  }

  // Check memory
  if (process.memoryUsage) {
    const memUsage = process.memoryUsage()
    requirements.memory = {
      available: memUsage.heapUsed < PERFORMANCE_REQUIREMENTS.MEMORY_LIMIT_MB * 1024 * 1024,
      usage: Math.round(memUsage.heapUsed / (1024 * 1024)),
    }
  }

  // Check dependencies
  try {
    require.resolve('tweetnacl')
    requirements.dependencies.tweetnacl = true
  } catch (error) {
    // tweetnacl not available
  }

  return requirements
}

// Main export - default credential manager instance
const defaultManager = new CredentialManager()
export default defaultManager
