#!/usr/bin/env bash

# Script to add predeployed WETH9 and WETH10 to genesis.json
# 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

# Check if contracts are compiled
if [ ! -f "$PROJECT_ROOT/out/tokens/WETH.sol/WETH.json" ]; then
    log_warn "WETH9 not compiled. Compiling..."
    cd "$PROJECT_ROOT"
    forge build --contracts contracts/tokens/WETH.sol 2>&1 | grep -E "(Compiling|Error)" || true
fi

if [ ! -f "$PROJECT_ROOT/out/tokens/WETH10.sol/WETH10.json" ]; then
    log_warn "WETH10 not compiled. Compiling..."
    cd "$PROJECT_ROOT"
    forge build --contracts contracts/tokens/WETH10.sol 2>&1 | grep -E "(Compiling|Error)" || true
fi

# Extract bytecode
WETH9_BYTECODE=$(jq -r '.bytecode.object' "$PROJECT_ROOT/out/tokens/WETH.sol/WETH.json" 2>/dev/null || echo "")
WETH10_BYTECODE=$(jq -r '.bytecode.object' "$PROJECT_ROOT/out/tokens/WETH10.sol/WETH10.json" 2>/dev/null || echo "")

if [ -z "$WETH9_BYTECODE" ] || [ "$WETH9_BYTECODE" == "null" ] || [ "$WETH9_BYTECODE" == "" ]; then
    log_error "Error: Could not extract WETH9 bytecode"
    echo "Please ensure contracts are compiled: forge build"
    exit 1
fi

if [ -z "$WETH10_BYTECODE" ] || [ "$WETH10_BYTECODE" == "null" ] || [ "$WETH10_BYTECODE" == "" ]; then
    log_error "Error: Could not extract WETH10 bytecode"
    echo "Please ensure contracts are compiled: forge build"
    exit 1
fi

log_success "Extracted 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!"
