#!/usr/bin/env bash
# Verify WETH9 at canonical address on ChainID 138
# Tests ERC-20 functions: symbol, decimals, name, totalSupply, balanceOf, approve, transfer
# Usage: ./verify-weth-canonical-erc20.sh

set -euo pipefail

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

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

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[✓]${NC} $1"; }
log_error() { echo -e "${RED}[✗]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[⚠]${NC} $1"; }
log_section() { echo -e "\n${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"; echo -e "${CYAN}$1${NC}"; echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}\n"; }

# Configuration
CHAIN138_RPC="${RPC_URL_138:-https://rpc-http-pub.d-bis.org}"
WETH_CANONICAL="0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"

# Test results
TESTS_PASSED=0
TESTS_FAILED=0
TESTS_TOTAL=0

log_section "WETH9 ERC-20 Verification at Canonical Address"

log_info "WETH9 Address: $WETH_CANONICAL"
log_info "ChainID: 138"
log_info "RPC URL: $CHAIN138_RPC"
log_info ""

# Check if cast is available
if ! command -v cast &> /dev/null; then
    log_error "cast (foundry) is not installed"
    log_warn "Please install foundry: curl -L https://foundry.paradigm.xyz | bash"
    exit 1
fi

# Test function
test_erc20_function() {
    local func_name=$1
    local func_sig=$2
    local expected_result=$3
    local description=$4
    
    ((TESTS_TOTAL++))
    log_info "Testing $func_name()..."
    
    local result=$(cast call "$WETH_CANONICAL" "$func_sig" --rpc-url "$CHAIN138_RPC" 2>&1 || echo "ERROR")
    
    if [[ "$result" == *"ERROR"* ]] || [ -z "$result" ] || [ "$result" = "0x" ]; then
        log_error "   ❌ $func_name() failed or returned empty"
        log_error "   Result: $result"
        ((TESTS_FAILED++))
        return 1
    else
        if [ "$func_name" = "symbol" ] || [ "$func_name" = "name" ]; then
            local clean_result=$(echo "$result" | cast --to-ascii 2>/dev/null | tr -d '\0' || echo "$result")
            log_success "   ✅ $func_name() = $clean_result"
        elif [ "$func_name" = "decimals" ]; then
            local dec_result=$(cast --to-dec "$result" 2>/dev/null || echo "unknown")
            if [ "$dec_result" = "18" ]; then
                log_success "   ✅ decimals() = $dec_result (expected: 18)"
            else
                log_warn "   ⚠ decimals() = $dec_result (expected: 18)"
            fi
        else
            local dec_result=$(cast --to-dec "$result" 2>/dev/null || echo "$result")
            log_success "   ✅ $func_name() = $dec_result"
        fi
        ((TESTS_PASSED++))
        return 0
    fi
}

# Step 1: Check bytecode
log_section "Step 1: Bytecode Verification"

log_info "Checking bytecode using eth_getCode..."
BYTECODE=$(cast code "$WETH_CANONICAL" --rpc-url "$CHAIN138_RPC" 2>/dev/null || echo "")

if [ -z "$BYTECODE" ] || [ "$BYTECODE" = "0x" ]; then
    log_error "❌ No bytecode found at WETH9 canonical address"
    log_error "   This means the contract is NOT deployed at this address on-chain"
    log_error "   However, genesis.json shows it should be predeployed"
    log_warn "   Possible reasons:"
    log_warn "   1. Chain was not started with this genesis.json"
    log_warn "   2. RPC endpoint issue"
    log_warn "   3. Contract was removed/overwritten"
    exit 1
else
    BYTECODE_LENGTH=$((${#BYTECODE} - 2))
    BYTECODE_BYTES=$((BYTECODE_LENGTH / 2))
    log_success "✅ Bytecode exists at WETH9 canonical address"
    log_info "   Bytecode length: $BYTECODE_LENGTH chars ($BYTECODE_BYTES bytes)"
fi

# Step 2: ERC-20 Function Tests
log_section "Step 2: ERC-20 Function Verification"

log_info "Testing standard ERC-20 functions..."
log_info ""

# Test symbol()
test_erc20_function "symbol" "symbol()" "" "Token symbol"

# Test name()
test_erc20_function "name" "name()" "" "Token name"

# Test decimals()
test_erc20_function "decimals" "decimals()" "18" "Token decimals (should be 18)"

# Test totalSupply()
test_erc20_function "totalSupply" "totalSupply()" "" "Total supply"

# Test balanceOf (test with zero address)
log_info "Testing balanceOf(address(0))..."
((TESTS_TOTAL++))
BALANCE_RESULT=$(cast call "$WETH_CANONICAL" "balanceOf(address)" "0x0000000000000000000000000000000000000000" --rpc-url "$CHAIN138_RPC" 2>&1 || echo "ERROR")
if [[ "$BALANCE_RESULT" == *"ERROR"* ]]; then
    log_error "   ❌ balanceOf() failed"
    ((TESTS_FAILED++))
else
    BALANCE_DEC=$(cast --to-dec "$BALANCE_RESULT" 2>/dev/null || echo "unknown")
    log_success "   ✅ balanceOf(address(0)) = $BALANCE_DEC"
    ((TESTS_PASSED++))
fi

# Summary
log_section "Verification Summary"

log_info "Tests Passed: $TESTS_PASSED / $TESTS_TOTAL"
log_info "Tests Failed: $TESTS_FAILED / $TESTS_TOTAL"
log_info ""

if [ $TESTS_FAILED -eq 0 ]; then
    log_success "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    log_success "✅ ALL ERC-20 TESTS PASSED"
    log_success "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    log_info ""
    log_info "WETH9 at canonical address is a valid ERC-20 token"
    log_info "Ready for bridge routing verification"
    exit 0
else
    log_warn "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    log_warn "⚠ SOME TESTS FAILED"
    log_warn "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    log_info ""
    log_warn "WETH9 may not be fully ERC-20 compliant or RPC issues occurred"
    exit 1
fi
