/**
 * Credential Manager Usage Examples
 *
 * Examples demonstrating how to use the multi-platform credential manager
 * for hedging operations across Pacifica, Aster, and Binance platforms.
 */

import { CredentialManager } from '@/core/credential-manager'
import { Platform, LoadResult } from '@/types/credential'

// ============================================================================
// Example 1: Basic Usage with Configuration Loading
// ============================================================================

export async function basicUsageExample() {
  console.log('🚀 Example 1: Basic Credential Manager Usage')
  console.log('=' .repeat(50))

  // Create credential manager instance
  const manager = new CredentialManager()

  try {
    // Load configuration from file
    const result: LoadResult = await manager.loadConfig('./config/accounts.json')

    if (result.success) {
      console.log('✅ Configuration loaded successfully')
      console.log(`📊 Loaded ${result.accounts.length} accounts in ${result.loadTime}ms`)

      // List all accounts
      const accounts = manager.listAccounts()
      console.log('\n📋 Available accounts:')
      accounts.forEach(account => {
        console.log(`  - ${account.id} (${account.platform}): ${account.name}`)
      })
    } else {
      console.error('❌ Configuration load failed:', result.errors)
    }
  } catch (error) {
    console.error('💥 Error:', error instanceof Error ? error.message : 'Unknown error')
  }
}

// ============================================================================
// Example 2: Multi-Platform Signing for Hedging
// ============================================================================

export async function hedgingSigningExample() {
  console.log('\n🔐 Example 2: Multi-Platform Signing for Hedging')
  console.log('=' .repeat(50))

  const manager = new CredentialManager()
  await manager.loadConfig('./config/accounts.json')

  // Sample trading message for each platform
  const tradingMessages = {
    pacifica: new TextEncoder().encode('PLACE_ORDER:BUY:SOL/USDC:100:45.50'),
    aster: new TextEncoder().encode('SWAP:ETH:USDT:1.5:3500'),
    binance: new TextEncoder().encode('LIMIT_ORDER:SELL:BTC/USDT:0.01:65000')
  }

  const accounts = manager.listAccounts()

  console.log('\n🎯 Executing hedging operations across platforms:')

  for (const account of accounts) {
    if (!account.enabled) continue

    const platform = account.platform as keyof typeof tradingMessages
    const message = tradingMessages[platform]

    if (message) {
      try {
        const startTime = Date.now()
        const signResult = await manager.sign(account.id, message)
        const duration = Date.now() - startTime

        if (signResult.success) {
          console.log(`✅ ${platform.toUpperCase()}: Signed in ${duration}ms`)
          console.log(`   Account: ${account.id}`)
          console.log(`   Algorithm: ${signResult.algorithm}`)
          console.log(`   Signature: ${signResult.signature?.substring(0, 20)}...`)
        } else {
          console.log(`❌ ${platform.toUpperCase()}: Signing failed - ${signResult.error}`)
        }
      } catch (error) {
        console.log(`💥 ${platform.toUpperCase()}: Exception - ${error instanceof Error ? error.message : 'Unknown'}`)
      }
    }
  }
}

// ============================================================================
// Example 3: Hot Configuration Reload for Live Trading
// ============================================================================

export async function hotReloadExample() {
  console.log('\n🔄 Example 3: Hot Configuration Reload')
  console.log('=' .repeat(50))

  const manager = new CredentialManager()

  // Set up configuration file watcher
  manager.watchConfig('./config/accounts.json', (accounts) => {
    console.log(`🔄 Configuration reloaded: ${accounts.length} accounts`)
    accounts.forEach(account => {
      console.log(`  - ${account.id}: ${account.status}`)
    })
  })

  console.log('👂 Watching for configuration changes...')
  console.log('   Modify ./config/accounts.json to see hot reload in action')

  // Simulate some activity
  await new Promise(resolve => setTimeout(resolve, 2000))

  // Stop watching
  manager.stopWatching()
  console.log('⏹️  Stopped watching configuration changes')
}

// ============================================================================
// Example 4: Performance Monitoring for High-Frequency Trading
// ============================================================================

export async function performanceMonitoringExample() {
  console.log('\n⚡ Example 4: Performance Monitoring')
  console.log('=' .repeat(50))

  const manager = new CredentialManager()
  await manager.loadConfig('./config/accounts.json')

  const testMessage = new TextEncoder().encode('PERFORMANCE_TEST_MESSAGE')
  const iterations = 10

  console.log(`🏃 Running ${iterations} signing operations for performance testing...`)

  const results: Array<{ accountId: string, duration: number, success: boolean }> = []

  const accounts = manager.listAccounts().filter(acc => acc.enabled)

  for (const account of accounts) {
    console.log(`\n📊 Testing ${account.platform.toUpperCase()} performance:`)

    for (let i = 0; i < iterations; i++) {
      const startTime = Date.now()
      const signResult = await manager.sign(account.id, testMessage)
      const duration = Date.now() - startTime

      results.push({
        accountId: account.id,
        duration,
        success: signResult.success
      })

      process.stdout.write(`  ${i + 1}/${iterations}: ${duration}ms `)
    }

    // Calculate statistics
    const accountResults = results.filter(r => r.accountId === account.id)
    const successfulResults = accountResults.filter(r => r.success)
    const avgTime = successfulResults.reduce((sum, r) => sum + r.duration, 0) / successfulResults.length
    const maxTime = Math.max(...successfulResults.map(r => r.duration))
    const minTime = Math.min(...successfulResults.map(r => r.duration))

    console.log(`\n   📈 Results: Avg: ${avgTime.toFixed(1)}ms, Min: ${minTime}ms, Max: ${maxTime}ms`)
    console.log(`   ✅ Success rate: ${successfulResults.length}/${accountResults.length}`)

    // Check performance requirements
    if (avgTime < 50) {
      console.log('   🎯 Performance requirement met (<50ms)')
    } else {
      console.log('   ⚠️  Performance requirement not met (>50ms)')
    }
  }
}

// ============================================================================
// Example 5: Error Handling and Retry Logic
// ============================================================================

export async function errorHandlingExample() {
  console.log('\n🛡️  Example 5: Error Handling and Retry Logic')
  console.log('=' .repeat(50))

  const manager = new CredentialManager()

  // Test with invalid configuration
  console.log('🧪 Testing error handling with invalid configuration...')

  try {
    const result = await manager.loadConfig('./config/nonexistent.json')
    if (!result.success) {
      console.log('✅ Properly handled missing configuration file')
      console.log('   Errors:', result.errors)
    }
  } catch (error) {
    console.log('✅ Caught configuration error:', error instanceof Error ? error.message : 'Unknown')
  }

  // Test with invalid account ID
  console.log('\n🧪 Testing signing with invalid account ID...')

  try {
    const signResult = await manager.sign('nonexistent-account', new Uint8Array([1, 2, 3]))
    if (!signResult.success) {
      console.log('✅ Properly handled invalid account ID')
      console.log('   Error:', signResult.error)
    }
  } catch (error) {
    console.log('✅ Caught signing error:', error instanceof Error ? error.message : 'Unknown')
  }
}

// ============================================================================
// Example 6: Integration with Trading System
// ============================================================================

export async function tradingIntegrationExample() {
  console.log('\n🔗 Example 6: Trading System Integration')
  console.log('=' .repeat(50))

  const manager = new CredentialManager()
  await manager.loadConfig('./config/accounts.json')

  // Simulate a hedging scenario
  const hedgingScenario = {
    // Long position on Pacifica
    pacifica: {
      action: 'BUY',
      symbol: 'SOL/USDC',
      amount: 100,
      price: 45.50
    },
    // Short position on Binance for hedge
    binance: {
      action: 'SELL',
      symbol: 'SOL/USDT',
      amount: 100,
      price: 45.60
    }
  }

  console.log('🎯 Executing delta-neutral hedging strategy:')

  for (const [platform, trade] of Object.entries(hedgingScenario)) {
    const account = manager.listAccounts().find(acc =>
      acc.platform === platform && acc.enabled
    )

    if (account) {
      const orderMessage = new TextEncoder().encode(
        `${trade.action}:${trade.symbol}:${trade.amount}:${trade.price}`
      )

      try {
        const signResult = await manager.sign(account.id, orderMessage)

        if (signResult.success) {
          console.log(`✅ ${platform.toUpperCase()}: ${trade.action} ${trade.amount} ${trade.symbol} @ ${trade.price}`)
          console.log(`   Signature: ${signResult.signature?.substring(0, 20)}...`)

          // In real implementation, you would send this to the trading system
          console.log(`   📤 Ready to submit to ${platform} trading API`)
        } else {
          console.log(`❌ ${platform.toUpperCase()}: Failed to sign order - ${signResult.error}`)
        }
      } catch (error) {
        console.log(`💥 ${platform.toUpperCase()}: Exception - ${error instanceof Error ? error.message : 'Unknown'}`)
      }
    } else {
      console.log(`⚠️  ${platform.toUpperCase()}: No enabled account found`)
    }
  }
}

// ============================================================================
// Main Example Runner
// ============================================================================

export async function runAllExamples() {
  console.log('🎯 Credential Manager Examples')
  console.log('=' .repeat(70))
  console.log('Demonstrating multi-platform credential management for hedging operations')
  console.log('=' .repeat(70))

  try {
    await basicUsageExample()
    await hedgingSigningExample()
    await hotReloadExample()
    await performanceMonitoringExample()
    await errorHandlingExample()
    await tradingIntegrationExample()

    console.log('\n🎉 All examples completed successfully!')
    console.log('\n📋 Summary:')
    console.log('- ✅ Basic credential management')
    console.log('- ✅ Multi-platform signing')
    console.log('- ✅ Hot configuration reload')
    console.log('- ✅ Performance monitoring')
    console.log('- ✅ Error handling')
    console.log('- ✅ Trading system integration')

  } catch (error) {
    console.error('\n❌ Example execution failed:', error instanceof Error ? error.message : 'Unknown error')
  }
}

// Run examples if this file is executed directly
if (require.main === module) {
  runAllExamples()
}