#!/usr/bin/env bash
# Verify WETH9 1:1 ratio with ETH
# This script tests that depositing X ETH results in exactly X WETH9
# Usage: ./verify-weth9-ratio.sh [private_key] [test_amount]

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:-}}"
TEST_AMOUNT="${2:-0.001}"

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

log_info "========================================="
log_info "WETH9 1:1 Ratio Verification"
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 Amount: $TEST_AMOUNT ETH"
log_info "RPC URL: $RPC_URL"
log_info ""

# Step 1: Get initial balances
log_info "Step 1: Checking 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 ($INITIAL_ETH wei)"
log_info "Initial WETH9 Balance: $INITIAL_WETH9_ETH WETH ($INITIAL_WETH9 wei)"
log_info ""

# Check if sufficient ETH
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"
    exit 1
fi

REQUIRED_ETH=$(echo "scale=18; $TEST_AMOUNT + 0.01" | bc 2>/dev/null || echo "$TEST_AMOUNT")
if (( $(echo "$INITIAL_ETH_ETH < $REQUIRED_ETH" | bc -l 2>/dev/null || echo 1) )); then
    log_error "Insufficient ETH balance. Need at least $REQUIRED_ETH ETH (including gas)"
    exit 1
fi

# Step 2: Wrap ETH to WETH9
log_info "Step 2: Wrapping $TEST_AMOUNT ETH to WETH9..."
CURRENT_NONCE=$(cast nonce "$DEPLOYER" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")

WRAP_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 "$WRAP_TX" | grep -qE "transactionHash"; then
    TX_HASH=$(echo "$WRAP_TX" | grep -oE "transactionHash[[:space:]]+0x[0-9a-fA-F]{64}" | awk '{print $2}')
    log_success "✓ Wrap transaction sent: $TX_HASH"
    log_info "Waiting for confirmation..."
    sleep 15
else
    log_error "Failed to wrap ETH"
    log_info "Transaction output: $WRAP_TX"
    exit 1
fi

# Step 3: Check balances after wrap
log_info ""
log_info "Step 3: Checking balances after wrap..."
FINAL_ETH=$(cast balance "$DEPLOYER" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
FINAL_WETH9=$(cast call "$WETH9_ADDRESS" "balanceOf(address)" "$DEPLOYER" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")

FINAL_ETH_ETH=$(echo "scale=18; $FINAL_ETH / 1000000000000000000" | bc 2>/dev/null || echo "0")
FINAL_WETH9_ETH=$(echo "scale=18; $FINAL_WETH9 / 1000000000000000000" | bc 2>/dev/null || echo "0")

log_info "Final ETH Balance: $FINAL_ETH_ETH ETH ($FINAL_ETH wei)"
log_info "Final WETH9 Balance: $FINAL_WETH9_ETH WETH ($FINAL_WETH9 wei)"
log_info ""

# Step 4: Calculate differences
ETH_DIFF=$(echo "scale=18; $INITIAL_ETH - $FINAL_ETH" | bc 2>/dev/null || echo "0")
WETH9_DIFF=$(echo "scale=18; $FINAL_WETH9 - $INITIAL_WETH9" | bc 2>/dev/null || echo "0")

ETH_DIFF_ETH=$(echo "scale=18; $ETH_DIFF / 1000000000000000000" | bc 2>/dev/null || echo "0")
WETH9_DIFF_ETH=$(echo "scale=18; $WETH9_DIFF / 1000000000000000000" | bc 2>/dev/null || echo "0")

log_info "ETH Spent: $ETH_DIFF_ETH ETH ($ETH_DIFF wei)"
log_info "WETH9 Received: $WETH9_DIFF_ETH WETH ($WETH9_DIFF wei)"
log_info ""

# Step 5: Verify 1:1 ratio
log_info "Step 4: Verifying 1:1 ratio..."
log_info ""

# Calculate the ratio (should be exactly 1.0)
if [ "$WETH9_DIFF" != "0" ]; then
    RATIO=$(echo "scale=18; $WETH9_DIFF / $TEST_AMOUNT_WEI" | bc 2>/dev/null || echo "0")
    RATIO_PERCENT=$(echo "scale=6; $RATIO * 100" | bc 2>/dev/null || echo "0")
    
    log_info "Expected WETH9: $TEST_AMOUNT WETH ($TEST_AMOUNT_WEI wei)"
    log_info "Actual WETH9: $WETH9_DIFF_ETH WETH ($WETH9_DIFF wei)"
    log_info "Ratio: $RATIO ($RATIO_PERCENT%)"
    log_info ""
    
    # Check if ratio is exactly 1.0 (within 0.0001% tolerance for rounding)
    RATIO_DIFF=$(echo "scale=18; $RATIO - 1.0" | bc 2>/dev/null || echo "0")
    RATIO_DIFF_ABS=$(echo "scale=18; if ($RATIO_DIFF < 0) -($RATIO_DIFF) else $RATIO_DIFF" | bc 2>/dev/null || echo "0")
    
    # Tolerance: 0.0001% (0.000001 in ratio terms)
    TOLERANCE="0.000001"
    
    if (( $(echo "$RATIO_DIFF_ABS <= $TOLERANCE" | bc -l 2>/dev/null || echo 0) )); then
        log_success "✓ 1:1 Ratio Verified! (Ratio: $RATIO)"
        log_info "  ETH deposited: $TEST_AMOUNT ETH"
        log_info "  WETH9 received: $WETH9_DIFF_ETH WETH"
        log_info "  Difference: $ETH_DIFF_ETH ETH (gas fees)"
    else
        log_error "✗ Ratio Mismatch Detected!"
        log_error "  Expected ratio: 1.0"
        log_error "  Actual ratio: $RATIO"
        log_error "  Difference: $RATIO_DIFF"
        log_error ""
        log_error "This indicates the WETH9 contract is NOT maintaining a 1:1 ratio."
        log_error "Please investigate the contract implementation."
        exit 1
    fi
else
    log_error "No WETH9 was received. Transaction may have failed."
    exit 1
fi

# Step 6: Check contract balance
log_info ""
log_info "Step 5: Verifying contract backing..."
CONTRACT_ETH=$(cast balance "$WETH9_ADDRESS" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
TOTAL_SUPPLY=$(cast call "$WETH9_ADDRESS" "totalSupply()" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")

CONTRACT_ETH_ETH=$(echo "scale=18; $CONTRACT_ETH / 1000000000000000000" | bc 2>/dev/null || echo "0")
TOTAL_SUPPLY_ETH=$(echo "scale=18; $TOTAL_SUPPLY / 1000000000000000000" | bc 2>/dev/null || echo "0")

log_info "WETH9 Contract ETH Balance: $CONTRACT_ETH_ETH ETH"
log_info "WETH9 Total Supply: $TOTAL_SUPPLY_ETH WETH"

if [ "$CONTRACT_ETH" = "$TOTAL_SUPPLY" ]; then
    log_success "✓ Contract balance matches total supply (1:1 backing)"
else
    log_warn "⚠ Contract balance does not match total supply"
    log_warn "  This may indicate an issue with the contract implementation"
fi

log_info ""
log_success "Verification complete!"
