#!/usr/bin/env bash
# Compare local WETH9 with standard WETH9 implementation
# Checks function signatures and behavior
# Usage: ./compare-weth9-standard.sh

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)"
STANDARD_WETH9_MAINNET="0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"  # Same address on Ethereum mainnet

log_info "========================================="
log_info "WETH9 Standard Comparison"
log_info "========================================="
log_info ""

# Standard WETH9 function signatures
declare -A STANDARD_FUNCTIONS=(
    ["deposit()"]="0xd0e30db0"
    ["withdraw(uint256)"]="0x2e1a7d4d"
    ["totalSupply()"]="0x18160ddd"
    ["balanceOf(address)"]="0x70a08231"
    ["transfer(address,uint256)"]="0xa9059cbb"
    ["transferFrom(address,address,uint256)"]="0x23b872dd"
    ["approve(address,uint256)"]="0x095ea7b3"
    ["allowance(address,address)"]="0xdd62ed3e"
)

log_info "Local WETH9 Address: $WETH9_ADDRESS"
log_info "Standard WETH9 (Ethereum Mainnet): $STANDARD_WETH9_MAINNET"
log_info ""

# Get local contract bytecode
log_info "Step 1: Fetching local contract bytecode..."
LOCAL_BYTECODE=$(cast code "$WETH9_ADDRESS" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
if [ -z "$LOCAL_BYTECODE" ] || [ "$LOCAL_BYTECODE" = "0x" ]; then
    log_error "Failed to fetch local contract bytecode"
    exit 1
fi

LOCAL_BYTECODE_LENGTH=$(echo -n "$LOCAL_BYTECODE" | wc -c)
log_success "✓ Local bytecode fetched ($LOCAL_BYTECODE_LENGTH chars)"
log_info ""

# Check function signatures
log_info "Step 2: Checking function signatures..."
log_info ""

MATCHES=0
MISSING=0

for func_name in "${!STANDARD_FUNCTIONS[@]}"; do
    sig="${STANDARD_FUNCTIONS[$func_name]}"
    if echo "$LOCAL_BYTECODE" | grep -qi "$sig"; then
        log_success "✓ $func_name ($sig) - Found"
        ((MATCHES++)) || true
    else
        log_warn "⚠ $func_name ($sig) - Not found"
        ((MISSING++)) || true
    fi
done

log_info ""
log_info "Function Signature Check:"
log_info "  Matches: $MATCHES"
log_info "  Missing: $MISSING"

if [ $MISSING -eq 0 ]; then
    log_success "✓ All standard function signatures found"
else
    log_warn "⚠ Some standard function signatures are missing"
fi

log_info ""

# Check contract behavior
log_info "Step 3: Checking contract behavior..."

# Check totalSupply and contract balance
TOTAL_SUPPLY=$(cast call "$WETH9_ADDRESS" "totalSupply()" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
CONTRACT_BALANCE=$(cast balance "$WETH9_ADDRESS" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")

if [ "$TOTAL_SUPPLY" = "$CONTRACT_BALANCE" ]; then
    log_success "✓ Contract balance = Total supply (1:1 backing maintained)"
else
    log_error "✗ Contract balance ≠ Total supply (backing mismatch)"
    log_error "  This is NOT standard WETH9 behavior"
fi

log_info ""

# Check decimals
log_info "Step 4: Checking decimals() function..."
DECIMALS=$(cast call "$WETH9_ADDRESS" "decimals()" --rpc-url "$RPC_URL" 2>/dev/null || echo "ERROR")
if [ "$DECIMALS" != "ERROR" ]; then
    DECIMALS_DEC=$(cast --to-dec "$DECIMALS" 2>/dev/null || echo "N/A")
    if [ "$DECIMALS_DEC" = "18" ]; then
        log_success "✓ decimals() returns 18 (standard)"
    elif [ "$DECIMALS_DEC" = "0" ]; then
        log_warn "⚠ decimals() returns 0 (known WETH9 issue, not critical)"
    else
        log_warn "⚠ decimals() returns $DECIMALS_DEC (unexpected)"
    fi
else
    log_warn "⚠ decimals() function not callable (may not exist)"
fi

log_info ""

# Summary
log_info "========================================="
log_info "Comparison Summary"
log_info "========================================="
log_info ""

if [ $MISSING -eq 0 ] && [ "$TOTAL_SUPPLY" = "$CONTRACT_BALANCE" ]; then
    log_success "✓ Contract appears to match standard WETH9 implementation"
    log_info ""
    log_info "However, to be certain:"
    log_info "  1. Run verification script: ./scripts/verify-weth9-ratio.sh"
    log_info "  2. Run test suite: ./scripts/test-weth9-deposit.sh"
    log_info "  3. Compare bytecode hash with known WETH9 implementations"
else
    log_warn "⚠ Contract may differ from standard WETH9"
    log_info ""
    log_info "Differences found:"
    if [ $MISSING -gt 0 ]; then
        log_info "  - Missing function signatures: $MISSING"
    fi
    if [ "$TOTAL_SUPPLY" != "$CONTRACT_BALANCE" ]; then
        log_info "  - Backing mismatch (balance ≠ supply)"
    fi
    log_info ""
    log_info "Recommendations:"
    log_info "  1. Decompile bytecode for detailed analysis"
    log_info "  2. Test deposit() function with verification script"
    log_info "  3. Compare with canonical WETH9 source code"
fi

log_info ""
log_info "For bytecode comparison:"
log_info "  cast code $WETH9_ADDRESS --rpc-url $RPC_URL > local_weth9.bin"
log_info "  Compare hash: cast keccak local_weth9.bin"
