#!/bin/bash
# Fetch Runtime Bytecode from Mainnet
# Fetches runtime bytecode for contracts from Ethereum mainnet to use in genesis predeploy

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PHASE1_DIR="$SCRIPT_DIR/../"
PROJECT_ROOT="$(cd "$PHASE1_DIR/../../.." && pwd)"
GENESIS_FILE="$PHASE1_DIR/config/genesis-138.json"

# Load .env (try multiple locations)
ENV_FILE=""
for path in "$PROJECT_ROOT/.env" "$PHASE1_DIR/../../.env" "$HOME/.env"; do
    if [ -f "$path" ]; then
        ENV_FILE="$path"
        break
    fi
done

if [ -n "$ENV_FILE" ]; then
    export $(grep -v '^#' "$ENV_FILE" | grep -E "^(ETHEREUM_MAINNET_RPC)" | xargs)
fi

# Try multiple RPC endpoints
RPC_ENDPOINTS=(
    "${ETHEREUM_MAINNET_RPC:-}"
    "https://eth.llamarpc.com"
    "https://rpc.ankr.com/eth"
    "https://ethereum.publicnode.com"
    "https://eth-mainnet.public.blastapi.io"
)

MAINNET_RPC=""
for RPC in "${RPC_ENDPOINTS[@]}"; do
    if [ -n "$RPC" ]; then
        if cast code "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2" --rpc-url "$RPC" &>/dev/null; then
            MAINNET_RPC="$RPC"
            echo "Using RPC: $RPC"
            break
        fi
    fi
done

if [ -z "$MAINNET_RPC" ]; then
    echo "Error: Could not find working mainnet RPC endpoint"
    exit 1
fi

echo "=========================================="
echo "Fetch Runtime Bytecode from Mainnet"
echo "=========================================="
echo "RPC: $MAINNET_RPC"
echo ""

# Contract addresses
WETH9_ADDRESS="0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"
WETH10_ADDRESS="0xf4BB2e28688e89fCcE3c0580D37d36A7672E8A9f"
CCIP_ROUTER="0x80226fc0Ee2b096224EeAc085Bb9a8cba1146f7D"
CCIPWETH9_BRIDGE="0x3304b747E565a97ec8AC220b0B6A1f6ffDB837e6"
CCIPWETH10_BRIDGE="0x8078A09637e47Fa5Ed34F626046Ea2094a5CDE5e"
LINK_TOKEN="0x514910771AF9Ca656af840dff83E8264EcF986CA"

# Fetch bytecode
echo "Fetching bytecode from mainnet..."
WETH9_CODE=$(cast code "$WETH9_ADDRESS" --rpc-url "$MAINNET_RPC" 2>/dev/null | grep -v "Error\|Warning" || echo "")
WETH10_CODE=$(cast code "$WETH10_ADDRESS" --rpc-url "$MAINNET_RPC" 2>/dev/null | grep -v "Error\|Warning" || echo "")
CCIP_ROUTER_CODE=$(cast code "$CCIP_ROUTER" --rpc-url "$MAINNET_RPC" 2>/dev/null | grep -v "Error\|Warning" || echo "")
CCIPWETH9_BRIDGE_CODE=$(cast code "$CCIPWETH9_BRIDGE" --rpc-url "$MAINNET_RPC" 2>/dev/null | grep -v "Error\|Warning" || echo "")
CCIPWETH10_BRIDGE_CODE=$(cast code "$CCIPWETH10_BRIDGE" --rpc-url "$MAINNET_RPC" 2>/dev/null | grep -v "Error\|Warning" || echo "")
LINK_TOKEN_CODE=$(cast code "$LINK_TOKEN" --rpc-url "$MAINNET_RPC" 2>/dev/null | grep -v "Error\|Warning" || echo "")

# Check results
SUCCESS_COUNT=0
TOTAL=6

if [ -n "$WETH9_CODE" ] && [ "$WETH9_CODE" != "0x" ]; then
    echo "✓ WETH9 bytecode retrieved (${#WETH9_CODE} characters)"
    ((SUCCESS_COUNT++))
else
    echo "✗ WETH9 bytecode not available"
fi

if [ -n "$WETH10_CODE" ] && [ "$WETH10_CODE" != "0x" ]; then
    echo "✓ WETH10 bytecode retrieved (${#WETH10_CODE} characters)"
    ((SUCCESS_COUNT++))
else
    echo "✗ WETH10 bytecode not available"
fi

if [ -n "$CCIP_ROUTER_CODE" ] && [ "$CCIP_ROUTER_CODE" != "0x" ]; then
    echo "✓ CCIP Router bytecode retrieved (${#CCIP_ROUTER_CODE} characters)"
    ((SUCCESS_COUNT++))
else
    echo "✗ CCIP Router bytecode not available"
fi

if [ -n "$CCIPWETH9_BRIDGE_CODE" ] && [ "$CCIPWETH9_BRIDGE_CODE" != "0x" ]; then
    echo "✓ CCIP WETH9 Bridge bytecode retrieved (${#CCIPWETH9_BRIDGE_CODE} characters)"
    ((SUCCESS_COUNT++))
else
    echo "✗ CCIP WETH9 Bridge bytecode not available"
fi

if [ -n "$CCIPWETH10_BRIDGE_CODE" ] && [ "$CCIPWETH10_BRIDGE_CODE" != "0x" ]; then
    echo "✓ CCIP WETH10 Bridge bytecode retrieved (${#CCIPWETH10_BRIDGE_CODE} characters)"
    ((SUCCESS_COUNT++))
else
    echo "✗ CCIP WETH10 Bridge bytecode not available"
fi

if [ -n "$LINK_TOKEN_CODE" ] && [ "$LINK_TOKEN_CODE" != "0x" ]; then
    echo "✓ LINK Token bytecode retrieved (${#LINK_TOKEN_CODE} characters)"
    ((SUCCESS_COUNT++))
else
    echo "✗ LINK Token bytecode not available"
fi

echo ""
echo "Retrieved: $SUCCESS_COUNT/$TOTAL contracts"

if [ $SUCCESS_COUNT -eq 0 ]; then
    echo "Error: Could not retrieve any bytecode"
    exit 1
fi

# Update genesis file
echo ""
echo "Updating genesis file with retrieved bytecode..."

# Create backup
cp "$GENESIS_FILE" "$GENESIS_FILE.backup"

# Update using jq
if [ -n "$WETH9_CODE" ] && [ "$WETH9_CODE" != "0x" ]; then
    jq --arg addr "$WETH9_ADDRESS" --arg code "$WETH9_CODE" \
        '.alloc[$addr].code = $code' "$GENESIS_FILE" > "$GENESIS_FILE.tmp" && mv "$GENESIS_FILE.tmp" "$GENESIS_FILE"
    echo "✓ Updated WETH9"
fi

if [ -n "$WETH10_CODE" ] && [ "$WETH10_CODE" != "0x" ]; then
    jq --arg addr "$WETH10_ADDRESS" --arg code "$WETH10_CODE" \
        '.alloc[$addr].code = $code' "$GENESIS_FILE" > "$GENESIS_FILE.tmp" && mv "$GENESIS_FILE.tmp" "$GENESIS_FILE"
    echo "✓ Updated WETH10"
fi

if [ -n "$CCIP_ROUTER_CODE" ] && [ "$CCIP_ROUTER_CODE" != "0x" ]; then
    jq --arg addr "$CCIP_ROUTER" --arg code "$CCIP_ROUTER_CODE" \
        '.alloc[$addr].code = $code' "$GENESIS_FILE" > "$GENESIS_FILE.tmp" && mv "$GENESIS_FILE.tmp" "$GENESIS_FILE"
    echo "✓ Updated CCIP Router"
fi

if [ -n "$CCIPWETH9_BRIDGE_CODE" ] && [ "$CCIPWETH9_BRIDGE_CODE" != "0x" ]; then
    jq --arg addr "$CCIPWETH9_BRIDGE" --arg code "$CCIPWETH9_BRIDGE_CODE" \
        '.alloc[$addr].code = $code' "$GENESIS_FILE" > "$GENESIS_FILE.tmp" && mv "$GENESIS_FILE.tmp" "$GENESIS_FILE"
    echo "✓ Updated CCIP WETH9 Bridge"
fi

if [ -n "$CCIPWETH10_BRIDGE_CODE" ] && [ "$CCIPWETH10_BRIDGE_CODE" != "0x" ]; then
    jq --arg addr "$CCIPWETH10_BRIDGE" --arg code "$CCIPWETH10_BRIDGE_CODE" \
        '.alloc[$addr].code = $code' "$GENESIS_FILE" > "$GENESIS_FILE.tmp" && mv "$GENESIS_FILE.tmp" "$GENESIS_FILE"
    echo "✓ Updated CCIP WETH10 Bridge"
fi

if [ -n "$LINK_TOKEN_CODE" ] && [ "$LINK_TOKEN_CODE" != "0x" ]; then
    jq --arg addr "$LINK_TOKEN" --arg code "$LINK_TOKEN_CODE" \
        '.alloc[$addr].code = $code' "$GENESIS_FILE" > "$GENESIS_FILE.tmp" && mv "$GENESIS_FILE.tmp" "$GENESIS_FILE"
    echo "✓ Updated LINK Token"
fi

echo ""
echo "=========================================="
echo "Genesis File Updated"
echo "=========================================="
echo "Backup saved to: $GENESIS_FILE.backup"
echo "Updated file: $GENESIS_FILE"
echo ""
echo "Note: Storage layouts may need to be filled in manually"
echo "      See config/GENESIS_PREDEPLOY_INSTRUCTIONS.md"

