#!/usr/bin/env bash

# Comprehensive Mainnet deployment script
# Deploys all required contracts to Ethereum Mainnet in correct order

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/../lib/init.sh"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
# 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 variables
if [ -f "$PROJECT_ROOT/.env" ]; then
    source "$PROJECT_ROOT/.env"
else
    log_error "Error: .env file not found"
    exit 1
fi

log_info "=== Ethereum Mainnet Deployment ==="

# Check wallet balances first (warning only)
log_warn "Step 1: Checking wallet balances..."
if ! "$SCRIPT_DIR/check-wallet-balances.sh" > /dev/null 2>&1; then
    log_warn "⚠️  Warning: Wallet balance check failed"
    log_warn "Proceeding anyway - ensure wallet has sufficient ETH for gas"
    echo "Run: ./scripts/deployment/check-wallet-balances.sh for details"
else
    log_success "✅ Wallet balances sufficient"
fi

# Configuration
# Use ETHEREUM_MAINNET_RPC; when Infura + INFURA_PROJECT_SECRET set, use Basic Auth URL for private key transactions
MAINNET_RPC="${MAINNET_RPC_URL:-${ETHEREUM_MAINNET_RPC:-https://eth.llamarpc.com}}"
if [[ "$MAINNET_RPC" == *"infura.io"* ]] && [[ -n "${INFURA_PROJECT_SECRET:-}" ]] && [[ ! "${INFURA_PROJECT_SECRET}" =~ \$\{ ]]; then
    # Build Infura URL with Basic Auth so cast/forge can send transactions
    [[ -f "$SCRIPT_DIR/../lib/infura.sh" ]] && source "$SCRIPT_DIR/../lib/infura.sh"
    _with_auth=$(build_infura_rpc "mainnet" 2>/dev/null || true)
    [[ -n "$_with_auth" ]] && MAINNET_RPC="$_with_auth" && log_info "Using Infura Mainnet RPC with Basic Auth"
fi
MAINNET_PRIVATE_KEY="${PRIVATE_KEY}"
MAINNET_CCIP_ROUTER="${MAINNET_CCIP_ROUTER:-0x80226fc0Ee2b096224EeAc085Bb9a8cba1146f7D}"  # Official Chainlink CCIP Router
MAINNET_LINK_TOKEN="${MAINNET_LINK_TOKEN:-0x514910771AF9Ca656af840dff83E8264EcF986CA}"
WETH9_ADDRESS="0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"
WETH10_ADDRESS="0xf4BB2e28688e89fCcE3c0580D37d36A7672E8A9f"

echo "Configuration:"
echo "  RPC: $MAINNET_RPC"
echo "  CCIP Router: $MAINNET_CCIP_ROUTER"
echo "  LINK Token: $MAINNET_LINK_TOKEN"
echo "  WETH9: $WETH9_ADDRESS"
echo "  WETH10: $WETH10_ADDRESS"

# Function to extract deployed address from forge output
extract_address() {
    local output="$1"
    echo "$output" | grep -E "Deployed to:|Contract deployed at:" | tail -1 | awk '{print $NF}' | tr -d '\n' || echo ""
}

# Function to deploy contract
deploy_contract() {
    local script_name=$1
    local contract_name=$2
    local extra_args="${3:-}"
    
    log_warn "Deploying $contract_name..."
    
    # Ensure private key has 0x prefix
    local private_key="$MAINNET_PRIVATE_KEY"
    if [[ ! "$private_key" =~ ^0x ]]; then
        private_key="0x$private_key"
    fi
    
    local output=$(forge script "$script_name" \
        --rpc-url "$MAINNET_RPC" \
        --broadcast \
        --private-key "$private_key" \
        $extra_args \
        2>&1)
    
    local address=$(extract_address "$output")
    
    if [ -z "$address" ]; then
        log_error "Error: Failed to deploy $contract_name"
        echo "$output" | tail -30
        return 1
    fi
    
    log_success "✅ $contract_name deployed at: $address"
    echo "$address"
}

# Deploy CCIPWETH9Bridge
log_info "Step 2: Deploying CCIPWETH9Bridge..."
export CCIP_ROUTER="$MAINNET_CCIP_ROUTER"
export CCIP_FEE_TOKEN="$MAINNET_LINK_TOKEN"
WETH9_BRIDGE=$(deploy_contract "script/DeployCCIPWETH9Bridge.s.sol" "CCIPWETH9Bridge")
if [ -z "$WETH9_BRIDGE" ]; then
    exit 1
fi

# Deploy CCIPWETH10Bridge
log_info "Step 3: Deploying CCIPWETH10Bridge..."
WETH10_BRIDGE=$(deploy_contract "script/DeployCCIPWETH10Bridge.s.sol" "CCIPWETH10Bridge")
if [ -z "$WETH10_BRIDGE" ]; then
    exit 1
fi

# Update .env file
log_warn "Step 4: Updating .env file..."
if grep -q "MAINNET_CCIP_WETH9_BRIDGE=" "$PROJECT_ROOT/.env"; then
    sed -i "s|MAINNET_CCIP_WETH9_BRIDGE=.*|MAINNET_CCIP_WETH9_BRIDGE=$WETH9_BRIDGE|" "$PROJECT_ROOT/.env"
else
    echo "MAINNET_CCIP_WETH9_BRIDGE=$WETH9_BRIDGE" >> "$PROJECT_ROOT/.env"
fi

if grep -q "MAINNET_CCIP_WETH10_BRIDGE=" "$PROJECT_ROOT/.env"; then
    sed -i "s|MAINNET_CCIP_WETH10_BRIDGE=.*|MAINNET_CCIP_WETH10_BRIDGE=$WETH10_BRIDGE|" "$PROJECT_ROOT/.env"
else
    echo "MAINNET_CCIP_WETH10_BRIDGE=$WETH10_BRIDGE" >> "$PROJECT_ROOT/.env"
fi

if ! grep -q "MAINNET_CCIP_ROUTER=" "$PROJECT_ROOT/.env"; then
    echo "MAINNET_CCIP_ROUTER=$MAINNET_CCIP_ROUTER" >> "$PROJECT_ROOT/.env"
fi

if ! grep -q "MAINNET_LINK_TOKEN=" "$PROJECT_ROOT/.env"; then
    echo "MAINNET_LINK_TOKEN=$MAINNET_LINK_TOKEN" >> "$PROJECT_ROOT/.env"
fi

log_success "✅ .env file updated"

# Summary
log_success "=== Deployment Summary ==="
echo "Deployed Contracts:"
echo "  CCIPWETH9Bridge:  $WETH9_BRIDGE"
echo "  CCIPWETH10Bridge: $WETH10_BRIDGE"
echo "Configuration:"
echo "  CCIP Router: $MAINNET_CCIP_ROUTER"
echo "  LINK Token: $MAINNET_LINK_TOKEN"
log_warn "Next Steps:"
echo "  1. Verify contracts on Etherscan"
echo "  2. Configure bridge destinations"
echo "  3. Test cross-chain transfers"
