#!/usr/bin/env bash
# Deploy CCIPWETH9Bridge and CCIPWETH10Bridge contracts on ChainID 138
# Usage: ./deploy-bridge-contracts.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
RPC_URL="${RPC_URL_138:-https://rpc-core.d-bis.org}"
CCIP_ROUTER="${CCIP_CHAIN138_ROUTER:-0x8078A09637e47Fa5Ed34F626046Ea2094a5CDE5e}"
WETH9_ADDRESS="0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"
WETH10_ADDRESS="0xf4BB2e28688e89fCcE3c0580D37d36A7672E8A9f"
LINK_TOKEN="${CCIP_CHAIN138_LINK_TOKEN:-0x0000000000000000000000000000000000000000}"

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

log_info "========================================="
log_info "Deploy Bridge Contracts - ChainID 138"
log_info "========================================="
log_info ""
log_info "Configuration:"
log_info "  RPC URL: $RPC_URL"
log_info "  CCIP Router: $CCIP_ROUTER"
log_info "  WETH9: $WETH9_ADDRESS"
log_info "  WETH10: $WETH10_ADDRESS"
log_info "  Fee Token: ${LINK_TOKEN:-Native ETH}"
log_info ""

cd "$SOURCE_PROJECT"

# Deploy CCIPWETH9Bridge
log_info "Step 1: Deploying CCIPWETH9Bridge..."
if forge script script/DeployCCIPWETH9Bridge.s.sol:DeployCCIPWETH9Bridge \
    --rpc-url "$RPC_URL" \
    --private-key "$PRIVATE_KEY" \
    --broadcast \
    --legacy \
    --via-ir \
    --skip contracts/reserve/ReserveTokenIntegration.sol 2>&1 | tee /tmp/weth9-bridge-deploy.log; then
    
    # Extract deployed address
    WETH9_BRIDGE=$(grep -E "CCIPWETH9Bridge deployed at:|deployed at:" /tmp/weth9-bridge-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"
        
        # Update .env
        if grep -q "CCIPWETH9_BRIDGE_CHAIN138=" "$SOURCE_PROJECT/.env"; then
            sed -i "s|CCIPWETH9_BRIDGE_CHAIN138=.*|CCIPWETH9_BRIDGE_CHAIN138=$WETH9_BRIDGE|" "$SOURCE_PROJECT/.env"
        else
            echo "CCIPWETH9_BRIDGE_CHAIN138=$WETH9_BRIDGE" >> "$SOURCE_PROJECT/.env"
        fi
        log_success "✓ Updated .env with CCIPWETH9_BRIDGE_CHAIN138=$WETH9_BRIDGE"
    else
        log_warn "Could not extract WETH9 bridge address from deployment log"
        log_info "Please check /tmp/weth9-bridge-deploy.log and update .env manually"
    fi
else
    log_error "Failed to deploy CCIPWETH9Bridge"
    exit 1
fi

log_info ""

# Deploy CCIPWETH10Bridge
log_info "Step 2: Deploying CCIPWETH10Bridge..."
if forge script script/DeployCCIPWETH10Bridge.s.sol:DeployCCIPWETH10Bridge \
    --rpc-url "$RPC_URL" \
    --private-key "$PRIVATE_KEY" \
    --broadcast \
    --legacy \
    --via-ir \
    --skip contracts/reserve/ReserveTokenIntegration.sol 2>&1 | tee /tmp/weth10-bridge-deploy.log; then
    
    # Extract deployed address
    WETH10_BRIDGE=$(grep -E "CCIPWETH10Bridge deployed at:|deployed at:" /tmp/weth10-bridge-deploy.log | tail -1 | sed 's/.*at: //' | awk '{print $1}' | tr -d '\n' || echo "")
    
    if [ -n "$WETH10_BRIDGE" ] && [ "$WETH10_BRIDGE" != "0x" ]; then
        log_success "✓ CCIPWETH10Bridge deployed at: $WETH10_BRIDGE"
        
        # Update .env
        if grep -q "CCIPWETH10_BRIDGE_CHAIN138=" "$SOURCE_PROJECT/.env"; then
            sed -i "s|CCIPWETH10_BRIDGE_CHAIN138=.*|CCIPWETH10_BRIDGE_CHAIN138=$WETH10_BRIDGE|" "$SOURCE_PROJECT/.env"
        else
            echo "CCIPWETH10_BRIDGE_CHAIN138=$WETH10_BRIDGE" >> "$SOURCE_PROJECT/.env"
        fi
        log_success "✓ Updated .env with CCIPWETH10_BRIDGE_CHAIN138=$WETH10_BRIDGE"
    else
        log_warn "Could not extract WETH10 bridge address from deployment log"
        log_info "Please check /tmp/weth10-bridge-deploy.log and update .env manually"
    fi
else
    log_error "Failed to deploy CCIPWETH10Bridge"
    exit 1
fi

log_info ""
log_success "========================================="
log_success "Bridge Deployment Complete!"
log_success "========================================="
log_info ""
log_info "Deployed Contracts:"
log_info "  CCIPWETH9Bridge:  ${WETH9_BRIDGE:-Not extracted}"
log_info "  CCIPWETH10Bridge: ${WETH10_BRIDGE:-Not extracted}"
log_info ""
log_info "Next Steps:"
log_info "  1. Verify addresses in $SOURCE_PROJECT/.env"
log_info "  2. Run: bash scripts/configure-bridge-destinations.sh"
log_info ""

