#!/usr/bin/env bash

set -e

# Deploy CCIPWETH10Bridge to ChainID 138

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/../lib/init.sh"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"

# Load environment
if [ -f "$PROJECT_ROOT/.env" ]; then
    source "$PROJECT_ROOT/.env"
fi

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

# CCIP Configuration
CCIP_ROUTER="${CCIP_ROUTER:-}"
CCIP_FEE_TOKEN="${CCIP_FEE_TOKEN:-}"  # LINK token address

# WETH10 address (canonical Mainnet address or deployed address)
WETH10_ADDRESS="${WETH10_ADDRESS:-0xf4BB2e28688e89fCcE3c0580D37d36A7672E8A9F}"

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

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

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

echo "Deploying CCIPWETH10Bridge to ChainID 138..."
echo "RPC URL: $RPC_URL"
echo "CCIP Router: $CCIP_ROUTER"
echo "WETH10 Address: $WETH10_ADDRESS"
echo "Fee Token (LINK): $CCIP_FEE_TOKEN"

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

# Export environment variables for Foundry
export PRIVATE_KEY
export CCIP_ROUTER
export CCIP_FEE_TOKEN

forge script script/DeployCCIPWETH10Bridge.s.sol:DeployCCIPWETH10Bridge \
    --rpc-url "$RPC_URL" \
    --broadcast \
    --private-key "$PRIVATE_KEY" \
    --verify \
    -vvvv

echo "CCIPWETH10Bridge deployment complete!"
echo "Next steps:"
echo "1. Save the deployed bridge address to your .env file"
echo "2. Configure bridge destinations:"
echo "   ./scripts/deployment/configure-weth10-bridge.sh"

