#!/usr/bin/env bash

# Deploy WETH9 and WETH10 using CREATE to match genesis.json addresses
# This script uses vm.etch approach which works in fork/test mode

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
cd "$PROJECT_ROOT"
# Load .env via dotenv (RPC CR/LF trim). Fallback: raw source.
if [[ -f "$SCRIPT_DIR/../lib/deployment/dotenv.sh" ]]; then
  # shellcheck disable=SC1090
  source "$SCRIPT_DIR/../lib/deployment/dotenv.sh"
  load_deployment_env --repo-root "${PROJECT_ROOT:-$REPO_ROOT}"
elif [[ -n "${PROJECT_ROOT:-}" && -f "$PROJECT_ROOT/.env" ]]; then
  set -a
  # shellcheck disable=SC1090
  source "$PROJECT_ROOT/.env"
  set +a
elif [[ -n "${REPO_ROOT:-}" && -f "$REPO_ROOT/.env" ]]; then
  set -a
  # shellcheck disable=SC1090
  source "$REPO_ROOT/.env"
  set +a
fi

# Load environment

RPC_URL="${RPC_URL:-http://localhost:8545}"
PRIVATE_KEY="${PRIVATE_KEY:-}"

if [ -z "$PRIVATE_KEY" ]; then
    echo "Error: PRIVATE_KEY environment variable not set"
    exit 1
fi

# Ensure PRIVATE_KEY has 0x prefix
if [[ ! "$PRIVATE_KEY" =~ ^0x ]]; then
    export PRIVATE_KEY="0x$PRIVATE_KEY"
fi

echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "🚀 Deploying WETH9 and WETH10 using CREATE (vm.etch)"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
echo "⚠️  Note: vm.etch only works in fork/test mode, not in production broadcasts"
echo "   For production, use CREATE with calculated nonce"
echo ""
echo "RPC URL: $RPC_URL"
echo "Target Addresses:"
echo "  WETH9:  0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"
echo "  WETH10: 0xf4BB2e28688e89fCcE3c0580D37d36A7672E8A9f"
echo ""

# Check if contracts already exist
echo "🔍 Checking if contracts already exist..."
WETH9_CODE=$(cast code 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2 --rpc-url "$RPC_URL" 2>/dev/null || echo "")
WETH10_CODE=$(cast code 0xf4BB2e28688e89fCcE3c0580D37d36A7672E8A9f --rpc-url "$RPC_URL" 2>/dev/null || echo "")

if [ -n "$WETH9_CODE" ] && [ "$WETH9_CODE" != "0x" ]; then
    echo "✅ WETH9 already deployed at 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"
    WETH9_DEPLOYED=true
else
    echo "⚠️  WETH9 not deployed"
    WETH9_DEPLOYED=false
fi

if [ -n "$WETH10_CODE" ] && [ "$WETH10_CODE" != "0x" ]; then
    echo "✅ WETH10 already deployed at 0xf4BB2e28688e89fCcE3c0580D37d36A7672E8A9f"
    WETH10_DEPLOYED=true
else
    echo "⚠️  WETH10 not deployed"
    WETH10_DEPLOYED=false
fi

# Deploy if needed
if [ "$WETH9_DEPLOYED" = false ] || [ "$WETH10_DEPLOYED" = false ]; then
    echo ""
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    echo "📤 Deploying using vm.etch..."
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    
    # Try deploying in fork mode if possible
    if echo "$RPC_URL" | grep -q "fork"; then
        echo "✅ Fork mode detected - vm.etch will work"
        FORK_FLAG="--fork-url"
    else
        echo "⚠️  Not in fork mode - vm.etch may not work in broadcast"
        echo "   Trying anyway..."
        FORK_FLAG=""
    fi
    
    forge script script/DeployWETHToGenesisAddresses.s.sol:DeployWETHToGenesisAddresses \
        --rpc-url "$RPC_URL" \
        --broadcast \
        --private-key "$PRIVATE_KEY" \
        --legacy \
        -vvv 2>&1 | tee /tmp/weth-create-deploy.log
    
    if grep -q "Successfully deployed" /tmp/weth-create-deploy.log; then
        echo "✅ Deployment successful!"
    else
        echo "⚠️  Deployment may have failed - check /tmp/weth-create-deploy.log"
    fi
fi

echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "✅ Deployment Complete"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
echo "Verifying deployments..."

WETH9_CODE_FINAL=$(cast code 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2 --rpc-url "$RPC_URL" 2>/dev/null || echo "")
WETH10_CODE_FINAL=$(cast code 0xf4BB2e28688e89fCcE3c0580D37d36A7672E8A9f --rpc-url "$RPC_URL" 2>/dev/null || echo "")

if [ -n "$WETH9_CODE_FINAL" ] && [ "$WETH9_CODE_FINAL" != "0x" ]; then
    echo "✅ WETH9 verified at 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"
    cast call 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2 "name()" --rpc-url "$RPC_URL" 2>/dev/null || true
else
    echo "❌ WETH9 not found at target address"
fi

if [ -n "$WETH10_CODE_FINAL" ] && [ "$WETH10_CODE_FINAL" != "0x" ]; then
    echo "✅ WETH10 verified at 0xf4BB2e28688e89fCcE3c0580D37d36A7672E8A9f"
    cast call 0xf4BB2e28688e89fCcE3c0580D37d36A7672E8A9f "name()" --rpc-url "$RPC_URL" 2>/dev/null || true
else
    echo "❌ WETH10 not found at target address"
fi

echo ""
echo "📋 Next Steps:"
echo "   1. If deployment failed, try using fork mode: --fork-url \$RPC_URL"
echo "   2. Or calculate CREATE nonce: node scripts/utils/calculate-create-address.js"
echo "   3. Or use address mapping for deployed addresses"
echo ""

