#!/usr/bin/env bash
# Deploy CCIPWETH9Bridge to Ethereum Mainnet
# Usage: ./deploy-ccipweth9bridge-ethereum-mainnet.sh

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
SOURCE_PROJECT="/home/intlc/projects/smom-dbis-138"

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

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[✓]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }

# Check prerequisites
if [ ! -d "$SOURCE_PROJECT" ]; then
    log_error "Source project not found: $SOURCE_PROJECT"
    exit 1
fi

# Load environment variables
if [ -f "$SOURCE_PROJECT/.env" ]; then
    source "$SOURCE_PROJECT/.env"
else
    log_error ".env file not found in $SOURCE_PROJECT"
    exit 1
fi

# Required variables
ETHEREUM_MAINNET_RPC="${ETHEREUM_MAINNET_RPC:-}"
ETHERSCAN_API_KEY="${ETHERSCAN_API_KEY:-}"

if [ -z "$ETHEREUM_MAINNET_RPC" ]; then
    log_error "ETHEREUM_MAINNET_RPC not set in .env file"
    exit 1
fi

if [ -z "$ETHERSCAN_API_KEY" ]; then
    log_error "ETHERSCAN_API_KEY not set in .env file"
    exit 1
fi

if [ -z "${PRIVATE_KEY:-}" ]; then
    log_error "PRIVATE_KEY not set in .env file"
    exit 1
fi

# Ethereum Mainnet addresses
CCIP_ROUTER_MAINNET="0x80226fc0Ee2b096224EeAc085Bb9a8cba1146f7D"
WETH9_MAINNET="0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"
LINK_TOKEN_MAINNET="0x514910771AF9Ca656af840dff83E8264EcF986CA"

log_info "========================================="
log_info "Deploy CCIPWETH9Bridge to Ethereum Mainnet"
log_info "========================================="
log_info ""
log_info "Configuration:"
log_info "  Network: Ethereum Mainnet"
log_info "  RPC URL: ${ETHEREUM_MAINNET_RPC:0:50}..."
log_info "  CCIP Router: $CCIP_ROUTER_MAINNET"
log_info "  WETH9: $WETH9_MAINNET"
log_info "  Fee Token (LINK): $LINK_TOKEN_MAINNET"
log_info ""

# Confirm deployment (skip if AUTO_DEPLOY=yes)
if [ "${AUTO_DEPLOY:-}" != "yes" ]; then
    log_warn "⚠️  This will deploy to Ethereum Mainnet and cost real ETH!"
    read -p "Continue? (yes/no): " confirm
    if [ "$confirm" != "yes" ]; then
        log_info "Deployment cancelled"
        exit 0
    fi
else
    log_info "AUTO_DEPLOY=yes - proceeding without confirmation"
fi

cd "$SOURCE_PROJECT"

# Check balance
log_info "Checking deployer balance..."
DEPLOYER_ADDRESS=$(cast wallet address --private-key "$PRIVATE_KEY" 2>/dev/null || echo "")
if [ -n "$DEPLOYER_ADDRESS" ]; then
    BALANCE=$(cast balance "$DEPLOYER_ADDRESS" --rpc-url "$ETHEREUM_MAINNET_RPC" 2>/dev/null || echo "0")
    log_info "Deployer: $DEPLOYER_ADDRESS"
    log_info "Balance: $(cast --to-unit "$BALANCE" ether) ETH"
    
    BALANCE_ETH=$(cast --to-unit "$BALANCE" ether)
    BALANCE_INT=$(echo "$BALANCE_ETH" | cut -d. -f1)
    if [ -n "$BALANCE_INT" ] && [ "$BALANCE_INT" -lt 1 ] && [ "$(echo "$BALANCE_ETH < 0.01" | bc 2>/dev/null || echo "1")" = "1" ]; then
        log_warn "⚠️  Low balance! Deployment may fail."
        if [ "${AUTO_DEPLOY:-}" != "yes" ]; then
            read -p "Continue anyway? (yes/no): " confirm2
            if [ "$confirm2" != "yes" ]; then
                log_info "Deployment cancelled"
                exit 0
            fi
        else
            log_warn "Proceeding with low balance (AUTO_DEPLOY=yes)"
        fi
    fi
fi

log_info ""
log_info "Step 1: Deploying CCIPWETH9Bridge to Ethereum Mainnet..."

# Set environment variables for deployment script
export CCIP_ROUTER="$CCIP_ROUTER_MAINNET"
export CCIP_FEE_TOKEN="$LINK_TOKEN_MAINNET"

# Deploy with via-ir (same as Chain 138 deployment)
# Skip problematic contracts that aren't needed for bridge deployment
if forge script script/DeployCCIPWETH9Bridge.s.sol:DeployCCIPWETH9Bridge \
    --rpc-url "$ETHEREUM_MAINNET_RPC" \
    --private-key "$PRIVATE_KEY" \
    --broadcast \
    --via-ir \
    --optimizer-runs 200 \
    --skip contracts/reserve/ReserveTokenIntegration.sol \
    2>&1 | tee /tmp/weth9-bridge-mainnet-deploy.log; then
    
    # Extract deployed address
    WETH9_BRIDGE=$(grep -E "CCIPWETH9Bridge deployed at:|deployed at:" /tmp/weth9-bridge-mainnet-deploy.log | tail -1 | sed 's/.*at: //' | awk '{print $1}' | tr -d '\n' || echo "")
    
    if [ -n "$WETH9_BRIDGE" ] && [ "$WETH9_BRIDGE" != "0x" ]; then
        log_success "✓ CCIPWETH9Bridge deployed at: $WETH9_BRIDGE"
        
        # Get transaction hash
        TX_HASH=$(grep -E "Transaction hash:|tx hash:" /tmp/weth9-bridge-mainnet-deploy.log | tail -1 | sed 's/.*hash: //' | awk '{print $1}' | tr -d '\n' || echo "")
        if [ -n "$TX_HASH" ]; then
            log_info "Transaction hash: $TX_HASH"
            log_info "View on Etherscan: https://etherscan.io/tx/$TX_HASH"
        fi
        
        log_info ""
        log_info "Step 2: Verifying contract on Etherscan..."
        
        # Wait for transaction to be mined
        log_info "Waiting for transaction to be mined..."
        sleep 10
        
        # Verify on Etherscan
        CONSTRUCTOR_ARGS=$(cast abi-encode "constructor(address,address,address)" "$CCIP_ROUTER_MAINNET" "$WETH9_MAINNET" "$LINK_TOKEN_MAINNET" | sed 's/^0x//')
        
        if forge verify-contract \
            "$WETH9_BRIDGE" \
            contracts/ccip/CCIPWETH9Bridge.sol:CCIPWETH9Bridge \
            --etherscan-api-key "$ETHERSCAN_API_KEY" \
            --chain-id 1 \
            --num-of-optimizations 200 \
            --constructor-args "$CONSTRUCTOR_ARGS" \
            --compiler-version "0.8.20+commit.a1b79de6" \
            --via-ir \
            2>&1 | tee /tmp/weth9-bridge-mainnet-verify.log; then
            log_success "✓ Contract verification submitted!"
            log_info "View on Etherscan: https://etherscan.io/address/$WETH9_BRIDGE"
        else
            log_warn "⚠️  Automatic verification failed. Please verify manually:"
            log_info "  Contract: $WETH9_BRIDGE"
            log_info "  Constructor args: 0x$CONSTRUCTOR_ARGS"
            log_info "  Compiler: v0.8.20+commit.a1b79de6"
            log_info "  Optimization: 200 runs"
            log_info "  Via IR: Yes"
        fi
        
        # Update .env
        if grep -q "CCIPWETH9_BRIDGE_MAINNET=" "$SOURCE_PROJECT/.env"; then
            sed -i "s|CCIPWETH9_BRIDGE_MAINNET=.*|CCIPWETH9_BRIDGE_MAINNET=$WETH9_BRIDGE|" "$SOURCE_PROJECT/.env"
        else
            echo "CCIPWETH9_BRIDGE_MAINNET=$WETH9_BRIDGE" >> "$SOURCE_PROJECT/.env"
        fi
        log_success "✓ Updated .env with CCIPWETH9_BRIDGE_MAINNET=$WETH9_BRIDGE"
    else
        log_warn "Could not extract WETH9 bridge address from deployment log"
        log_info "Please check /tmp/weth9-bridge-mainnet-deploy.log and update .env manually"
    fi
else
    log_error "Failed to deploy CCIPWETH9Bridge"
    log_info "Check /tmp/weth9-bridge-mainnet-deploy.log for details"
    exit 1
fi

log_info ""
log_success "========================================="
log_success "Deployment Complete!"
log_success "========================================="
log_info ""
log_info "Deployed Contract:"
log_info "  CCIPWETH9Bridge: ${WETH9_BRIDGE:-Not extracted}"
log_info ""
log_info "Next Steps:"
log_info "  1. Verify contract on Etherscan (if auto-verify failed)"
log_info "  2. Configure bridge destinations"
log_info ""

