#!/usr/bin/env bash
# Test WETH9 deposit function with detailed analysis
# Tests multiple amounts to verify 1:1 ratio consistency
# Usage: ./test-weth9-deposit.sh [private_key] [test_amounts...]
# Example: ./test-weth9-deposit.sh 0x... 0.001 0.01 0.1

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
source "$PROJECT_ROOT/scripts/lib/address-inventory.sh"

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[✓]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }

load_explorer_runtime_env

# Configuration
RPC_URL="${RPC_URL_138:-http://192.168.11.250:8545}"
WETH9_ADDRESS="$(resolve_address_value WETH9_ADDRESS WETH9_ADDRESS 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2)"

# Parse arguments
PRIVATE_KEY="${1:-${PRIVATE_KEY:-}}"
shift || true
TEST_AMOUNTS=("${@:-0.001}")

if [ -z "$PRIVATE_KEY" ]; then
    log_error "PRIVATE_KEY not provided. Usage: $0 [private_key] [test_amounts...]"
    log_info "Or export PRIVATE_KEY before running"
    exit 1
fi

log_info "========================================="
log_info "WETH9 Deposit Function Test Suite"
log_info "========================================="
log_info ""

# Get deployer address
DEPLOYER=$(cast wallet address --private-key "$PRIVATE_KEY" 2>/dev/null || echo "")
if [ -z "$DEPLOYER" ]; then
    log_error "Failed to get address from private key"
    exit 1
fi

log_info "Wallet Address: $DEPLOYER"
log_info "Test Amounts: ${TEST_AMOUNTS[*]}"
log_info "RPC URL: $RPC_URL"
log_info ""

# Get initial balances
INITIAL_ETH=$(cast balance "$DEPLOYER" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
INITIAL_WETH9=$(cast call "$WETH9_ADDRESS" "balanceOf(address)" "$DEPLOYER" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")

INITIAL_ETH_ETH=$(echo "scale=18; $INITIAL_ETH / 1000000000000000000" | bc 2>/dev/null || echo "0")
INITIAL_WETH9_ETH=$(echo "scale=18; $INITIAL_WETH9 / 1000000000000000000" | bc 2>/dev/null || echo "0")

log_info "Initial ETH Balance: $INITIAL_ETH_ETH ETH"
log_info "Initial WETH9 Balance: $INITIAL_WETH9_ETH WETH"
log_info ""

# Test results storage
declare -a TEST_RESULTS
PASSED=0
FAILED=0

# Run tests for each amount
for TEST_AMOUNT in "${TEST_AMOUNTS[@]}"; do
    log_info "----------------------------------------"
    log_info "Testing with amount: $TEST_AMOUNT ETH"
    log_info "----------------------------------------"
    
    # Convert to wei
    TEST_AMOUNT_WEI=$(cast --to-wei "$TEST_AMOUNT" ether 2>/dev/null || echo "")
    if [ -z "$TEST_AMOUNT_WEI" ]; then
        log_error "Failed to convert $TEST_AMOUNT to wei"
        ((FAILED++)) || true
        continue
    fi
    
    # Get balance before
    ETH_BEFORE=$(cast balance "$DEPLOYER" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
    WETH9_BEFORE=$(cast call "$WETH9_ADDRESS" "balanceOf(address)" "$DEPLOYER" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
    
    # Check sufficient balance
    ETH_BEFORE_ETH=$(echo "scale=18; $ETH_BEFORE / 1000000000000000000" | bc 2>/dev/null || echo "0")
    REQUIRED=$(echo "scale=18; $TEST_AMOUNT + 0.01" | bc 2>/dev/null || echo "$TEST_AMOUNT")
    
    if (( $(echo "$ETH_BEFORE_ETH < $REQUIRED" | bc -l 2>/dev/null || echo 1) )); then
        log_warn "Insufficient ETH for test ($TEST_AMOUNT ETH). Skipping..."
        ((FAILED++)) || true
        continue
    fi
    
    # Execute deposit
    log_info "Executing deposit() with $TEST_AMOUNT ETH..."
    CURRENT_NONCE=$(cast nonce "$DEPLOYER" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
    
    DEPOSIT_TX=$(cast send "$WETH9_ADDRESS" "deposit()" \
        --value "$TEST_AMOUNT_WEI" \
        --rpc-url "$RPC_URL" \
        --private-key "$PRIVATE_KEY" \
        --gas-price 5000000000 \
        --nonce "$CURRENT_NONCE" \
        2>&1 || echo "")
    
    if ! echo "$DEPOSIT_TX" | grep -qE "transactionHash"; then
        log_error "Deposit transaction failed"
        log_info "Output: $DEPOSIT_TX"
        ((FAILED++)) || true
        continue
    fi
    
    TX_HASH=$(echo "$DEPOSIT_TX" | grep -oE "transactionHash[[:space:]]+0x[0-9a-fA-F]{64}" | awk '{print $2}')
    log_success "Transaction sent: $TX_HASH"
    log_info "Waiting for confirmation..."
    sleep 15
    
    # Get balance after
    ETH_AFTER=$(cast balance "$DEPLOYER" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
    WETH9_AFTER=$(cast call "$WETH9_ADDRESS" "balanceOf(address)" "$DEPLOYER" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
    
    # Calculate differences
    ETH_SPENT=$(echo "$ETH_BEFORE - $ETH_AFTER" | bc 2>/dev/null || echo "0")
    WETH9_RECEIVED=$(echo "$WETH9_AFTER - $WETH9_BEFORE" | bc 2>/dev/null || echo "0")
    
    ETH_SPENT_ETH=$(echo "scale=18; $ETH_SPENT / 1000000000000000000" | bc 2>/dev/null || echo "0")
    WETH9_RECEIVED_ETH=$(echo "scale=18; $WETH9_RECEIVED / 1000000000000000000" | bc 2>/dev/null || echo "0")
    
    # Calculate gas (approximate)
    GAS_ESTIMATE=$(echo "$ETH_SPENT - $TEST_AMOUNT_WEI" | bc 2>/dev/null || echo "0")
    GAS_ESTIMATE_ETH=$(echo "scale=18; $GAS_ESTIMATE / 1000000000000000000" | bc 2>/dev/null || echo "0")
    
    log_info "Results:"
    log_info "  ETH Spent (total): $ETH_SPENT_ETH ETH ($ETH_SPENT wei)"
    log_info "  ETH for Wrap: $TEST_AMOUNT ETH ($TEST_AMOUNT_WEI wei)"
    log_info "  Gas (approx): $GAS_ESTIMATE_ETH ETH ($GAS_ESTIMATE wei)"
    log_info "  WETH9 Received: $WETH9_RECEIVED_ETH WETH ($WETH9_RECEIVED wei)"
    log_info ""
    
    # Verify 1:1 ratio
    if [ "$WETH9_RECEIVED" = "$TEST_AMOUNT_WEI" ]; then
        log_success "✓ 1:1 Ratio VERIFIED for $TEST_AMOUNT ETH"
        TEST_RESULTS+=("$TEST_AMOUNT ETH: PASS")
        ((PASSED++)) || true
    else
        log_error "✗ 1:1 Ratio FAILED for $TEST_AMOUNT ETH"
        log_error "  Expected: $TEST_AMOUNT_WEI wei"
        log_error "  Received: $WETH9_RECEIVED wei"
        DIFF=$(echo "$TEST_AMOUNT_WEI - $WETH9_RECEIVED" | bc 2>/dev/null || echo "0")
        DIFF_ETH=$(echo "scale=18; $DIFF / 1000000000000000000" | bc 2>/dev/null || echo "0")
        log_error "  Difference: $DIFF_ETH ETH ($DIFF wei)"
        TEST_RESULTS+=("$TEST_AMOUNT ETH: FAIL (diff: $DIFF_ETH ETH)")
        ((FAILED++)) || true
    fi
    
    log_info ""
done

# Final summary
log_info "========================================="
log_info "Test Summary"
log_info "========================================="
log_info ""

for result in "${TEST_RESULTS[@]}"; do
    if echo "$result" | grep -q "PASS"; then
        log_success "$result"
    else
        log_error "$result"
    fi
done

log_info ""
log_info "Total Tests: $(($PASSED + $FAILED))"
log_info "Passed: $PASSED"
log_info "Failed: $FAILED"

if [ $FAILED -eq 0 ]; then
    log_success "✓ All tests passed - 1:1 ratio is maintained"
    exit 0
else
    log_error "✗ Some tests failed - 1:1 ratio is NOT maintained"
    log_info ""
    log_info "This indicates the WETH9 contract may have:"
    log_info "  - Fees deducted during deposit"
    log_info "  - Modified deposit() implementation"
    log_info "  - Accounting errors"
    log_info ""
    log_info "Recommendation: Inspect contract bytecode and compare with standard WETH9"
    exit 1
fi
