#!/usr/bin/env bash
# Load Testing Script
# Tests bridge system under load

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../../../../.." && pwd)"

source "$PROJECT_ROOT/.env" 2>/dev/null || true

RPC_URL="${CHAIN138_RPC:-${RPC_URL_138:-http://192.168.11.250:8545}}"
ETHEREUM_RPC="${ETHEREUM_MAINNET_RPC:-${ETHEREUM_RPC:-}}"

if [ -z "$ETHEREUM_RPC" ]; then
    echo "Error: ETHEREUM_MAINNET_RPC must be set"
    exit 1
fi

LOCKBOX138="${LOCKBOX138_ADDRESS:-}"
INBOX_ETH="${INBOX_ETH_ADDRESS:-}"

if [ -z "$LOCKBOX138" ] || [ -z "$INBOX_ETH" ]; then
    echo "Error: Contract addresses must be set"
    echo "Set LOCKBOX138_ADDRESS and INBOX_ETH_ADDRESS in .env"
    exit 1
fi

echo "Load Testing - Trustless Bridge"
echo "================================"
echo ""

# Test parameters
CONCURRENT_DEPOSITS="${1:-10}"
DEPOSIT_AMOUNT="${2:-0.1}"
TEST_DURATION="${3:-300}" # 5 minutes

echo "Test Parameters:"
echo "  Concurrent Deposits: $CONCURRENT_DEPOSITS"
echo "  Deposit Amount: $DEPOSIT_AMOUNT ETH"
echo "  Test Duration: $TEST_DURATION seconds"
echo ""

# Create load test script
LOAD_TEST_SCRIPT="$SCRIPT_DIR/load-test-runner.js"
cat > "$LOAD_TEST_SCRIPT" <<EOF
const { ethers } = require('ethers');

// Load test configuration
const CONFIG = {
    chain138Rpc: process.env.CHAIN138_RPC || '$RPC_URL',
    ethereumRpc: process.env.ETHEREUM_MAINNET_RPC || '$ETHEREUM_RPC',
    lockbox138: process.env.LOCKBOX138_ADDRESS || '$LOCKBOX138',
    inboxETH: process.env.INBOX_ETH_ADDRESS || '$INBOX_ETH',
    concurrentDeposits: $CONCURRENT_DEPOSITS,
    depositAmount: ethers.parseEther('$DEPOSIT_AMOUNT'),
    testDuration: $TEST_DURATION * 1000
};

async function loadTest() {
    console.log('Starting load test...');
    console.log('Configuration:', CONFIG);
    
    // Connect to networks
    const chain138Provider = new ethers.JsonRpcProvider(CONFIG.chain138Rpc);
    const ethereumProvider = new ethers.JsonRpcProvider(CONFIG.ethereumRpc);
    
    // Test connectivity
    const chain138Block = await chain138Provider.getBlockNumber();
    const ethereumBlock = await ethereumProvider.getBlockNumber();
    
    console.log(\`ChainID 138 block: \${chain138Block}\`);
    console.log(\`Ethereum block: \${ethereumBlock}\`);
    
    // Load test metrics
    const metrics = {
        depositsSubmitted: 0,
        depositsFailed: 0,
        claimsSubmitted: 0,
        claimsFailed: 0,
        averageLatency: 0,
        startTime: Date.now()
    };
    
    // Simulate concurrent deposits
    const depositPromises = [];
    for (let i = 0; i < CONFIG.concurrentDeposits; i++) {
        depositPromises.push(simulateDeposit(i, chain138Provider, metrics));
    }
    
    await Promise.allSettled(depositPromises);
    
    const endTime = Date.now();
    const duration = (endTime - metrics.startTime) / 1000;
    
    console.log('');
    console.log('Load Test Results:');
    console.log(\`  Duration: \${duration.toFixed(2)} seconds\`);
    console.log(\`  Deposits Submitted: \${metrics.depositsSubmitted}\`);
    console.log(\`  Deposits Failed: \${metrics.depositsFailed}\`);
    console.log(\`  Success Rate: \${((metrics.depositsSubmitted / CONFIG.concurrentDeposits) * 100).toFixed(2)}%\`);
}

async function simulateDeposit(index, provider, metrics) {
    try {
        const startTime = Date.now();
        
        // Simulate deposit (would use actual contract call in production)
        // For now, just simulate the operation
        await new Promise(resolve => setTimeout(resolve, 100 + Math.random() * 200));
        
        const latency = Date.now() - startTime;
        metrics.depositsSubmitted++;
        metrics.averageLatency = (metrics.averageLatency * (metrics.depositsSubmitted - 1) + latency) / metrics.depositsSubmitted;
        
        console.log(\`Deposit \${index + 1}: Success (latency: \${latency}ms)\`);
    } catch (error) {
        metrics.depositsFailed++;
        console.error(\`Deposit \${index + 1}: Failed - \${error.message}\`);
    }
}

loadTest().catch(console.error);
EOF

echo "Load test script created: $LOAD_TEST_SCRIPT"
echo ""
echo "To run load test:"
echo "  1. Install dependencies: npm install ethers"
echo "  2. Run: node $LOAD_TEST_SCRIPT"
echo ""
echo "For comprehensive load testing, consider:"
echo "  - k6 (https://k6.io/)"
echo "  - Apache JMeter"
echo "  - Custom testing framework"
echo ""
echo "Load testing should verify:"
echo "  - System handles concurrent deposits"
echo "  - Rate limiting works correctly"
echo "  - Gas costs remain reasonable"
echo "  - No performance degradation"
echo "  - Error handling under load"

