#!/usr/bin/env bash

# Script to add predeployed WETH9 and WETH10 to genesis.json using Mainnet bytecode
# This ensures they exist at their canonical Mainnet addresses

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/../lib/init.sh"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
GENESIS_FILE="$PROJECT_ROOT/config/genesis.json"
GENESIS_BACKUP="$GENESIS_FILE.backup.$(date +%Y%m%d_%H%M%S)"


# Canonical Mainnet addresses
WETH9_ADDRESS="0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"
WETH10_ADDRESS="0xf4BB2e28688e89fCcE3c0580D37d36A7672E8A9f"

log_success "Adding predeployed WETH9 and WETH10 to genesis.json"

# Backup genesis file
if [ -f "$GENESIS_FILE" ]; then
    cp "$GENESIS_FILE" "$GENESIS_BACKUP"
    log_warn "Backed up genesis.json to: $GENESIS_BACKUP"
fi

# Fetch bytecode from Mainnet if cast is available
if command -v cast &> /dev/null; then
    log_warn "Fetching bytecode from Ethereum Mainnet..."
    
    WETH9_BYTECODE=$(cast code "$WETH9_ADDRESS" --rpc-url https://eth.llamarpc.com 2>/dev/null || echo "")
    if [ -z "$WETH9_BYTECODE" ] || [ "$WETH9_BYTECODE" == "0x" ]; then
        log_warn "Trying alternative RPC..."
        WETH9_BYTECODE=$(cast code "$WETH9_ADDRESS" --rpc-url https://rpc.ankr.com/eth 2>/dev/null || echo "")
    fi
    
    WETH10_BYTECODE=$(cast code "$WETH10_ADDRESS" --rpc-url https://eth.llamarpc.com 2>/dev/null || echo "")
    if [ -z "$WETH10_BYTECODE" ] || [ "$WETH10_BYTECODE" == "0x" ]; then
        log_warn "Trying alternative RPC..."
        WETH10_BYTECODE=$(cast code "$WETH10_ADDRESS" --rpc-url https://rpc.ankr.com/eth 2>/dev/null || echo "")
    fi
else
    log_error "Error: cast not found. Please install Foundry (forge install)"
    exit 1
fi

if [ -z "$WETH9_BYTECODE" ] || [ "$WETH9_BYTECODE" == "0x" ]; then
    log_error "Error: Could not fetch WETH9 bytecode from Mainnet"
    exit 1
fi

if [ -z "$WETH10_BYTECODE" ] || [ "$WETH10_BYTECODE" == "0x" ]; then
    log_error "Error: Could not fetch WETH10 bytecode from Mainnet"
    exit 1
fi

log_success "Fetched bytecode:"
echo "  WETH9:  $(echo $WETH9_BYTECODE | wc -c) characters"
echo "  WETH10: $(echo $WETH10_BYTECODE | wc -c) characters"

# Use jq to add contracts to alloc
log_warn "Updating genesis.json..."
jq --arg addr "$WETH9_ADDRESS" \
   --arg code "$WETH9_BYTECODE" \
   --arg addr10 "$WETH10_ADDRESS" \
   --arg code10 "$WETH10_BYTECODE" \
   '.alloc[$addr] = {
     "code": $code,
     "balance": "0x0"
   } | .alloc[$addr10] = {
     "code": $code10,
     "balance": "0x0"
   }' "$GENESIS_FILE" > "$GENESIS_FILE.tmp" && mv "$GENESIS_FILE.tmp" "$GENESIS_FILE"

log_success "Successfully added predeployed contracts to genesis.json"
echo "Predeployed contracts:"
echo "  WETH9:  $WETH9_ADDRESS"
echo "  WETH10: $WETH10_ADDRESS"
log_warn "Note: These contracts will exist at their canonical Mainnet addresses"
log_warn "      when the chain starts. No deployment needed!"
