#!/usr/bin/env bash
# Complete CCIP Deployment Script for ChainID 138
# This script performs the complete CCIP deployment and configuration

set -e

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_138:-${CHAIN138_RPC_URL:-http://localhost:8545}}"
PRIVATE_KEY="${PRIVATE_KEY:-}"

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

log_info "=== CCIP Complete Deployment for ChainID 138 ==="
echo "RPC URL: $RPC_URL"
echo ""

# Verify RPC connectivity
if ! cast block-number --rpc-url "$RPC_URL" &>/dev/null; then
    log_error "Error: Cannot connect to RPC at $RPC_URL"
    exit 1
fi

CHAIN_ID=$(cast chain-id --rpc-url "$RPC_URL" 2>/dev/null || echo "unknown")
if [ "$CHAIN_ID" != "138" ]; then
    log_warn "⚠️  Warning: Chain ID is $CHAIN_ID, expected 138"
    read -p "Continue anyway? (y/N) " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        exit 1
    fi
fi

echo "Chain ID: $CHAIN_ID"
echo ""

# Step 1: Calculate Chain Selector
log_info "Step 1: Calculating chain selector..."
if [ -f "$PROJECT_ROOT/scripts/ccip/calculate-chain-selector.sh" ]; then
    bash "$PROJECT_ROOT/scripts/ccip/calculate-chain-selector.sh"
    log_success "✅ Chain selector calculated"
else
    log_warn "⚠️  Chain selector script not found, using default: 138"
    CHAIN138_SELECTOR="${CHAIN138_SELECTOR:-138}"
fi

# Step 2: Deploy CCIP Router
log_info "Step 2: Deploying CCIP Router..."
CCIP_ROUTER="${CCIP_CHAIN138_ROUTER:-}"

if [ -z "$CCIP_ROUTER" ] || [ "$CCIP_ROUTER" = "" ]; then
    log_info "Deploying CCIP Router..."
    
    # Set default fee configuration if not set
    export CCIP_FEE_TOKEN="${CCIP_CHAIN138_LINK_TOKEN:-0x0000000000000000000000000000000000000000}"
    export CCIP_BASE_FEE="${CCIP_BASE_FEE:-1000000000000000}"
    export CCIP_DATA_FEE_PER_BYTE="${CCIP_DATA_FEE_PER_BYTE:-100000000}"
    
    ROUTER_OUTPUT=$(forge script script/DeployCCIPRouter.s.sol \
        --rpc-url "$RPC_URL" \
        --broadcast \
        --private-key "$PRIVATE_KEY" 2>&1 || true)
    
    ROUTER_ADDRESS=$(echo "$ROUTER_OUTPUT" | grep -E "CCIP Router deployed at:|deployed at:" | tail -1 | sed 's/.*at: //' | awk '{print $1}' | tr -d '\n' || echo "")
    
    if [ -n "$ROUTER_ADDRESS" ] && [ "$ROUTER_ADDRESS" != "" ]; then
        CCIP_ROUTER="$ROUTER_ADDRESS"
        log_success "✅ CCIP Router deployed at: $CCIP_ROUTER"
        
        # Update .env
        if grep -q "^CCIP_CHAIN138_ROUTER=" "$PROJECT_ROOT/.env" 2>/dev/null; then
            sed -i.bak "s|^CCIP_CHAIN138_ROUTER=.*|CCIP_CHAIN138_ROUTER=$CCIP_ROUTER|" "$PROJECT_ROOT/.env"
        else
            echo "CCIP_CHAIN138_ROUTER=$CCIP_ROUTER" >> "$PROJECT_ROOT/.env"
        fi
        
        # Configure router
        log_info "Configuring CCIP Router..."
        export CCIP_CHAIN138_ROUTER="$CCIP_ROUTER"
        bash "$PROJECT_ROOT/scripts/deployment/configure-ccip-router.sh" || log_warn "⚠️  Router configuration had issues"
    else
        log_error "❌ Failed to deploy CCIP Router"
        exit 1
    fi
else
    log_success "✅ CCIP Router already deployed: $CCIP_ROUTER"
fi

# Step 3: Deploy CCIPWETH9Bridge
log_info "Step 3: Deploying CCIPWETH9Bridge..."
WETH9_BRIDGE="${CCIPWETH9_BRIDGE_CHAIN138:-}"

if [ -z "$WETH9_BRIDGE" ] || [ "$WETH9_BRIDGE" = "" ]; then
    log_info "Deploying CCIPWETH9Bridge..."
    
    export CCIP_ROUTER="$CCIP_ROUTER"
    export CCIP_FEE_TOKEN="${CCIP_CHAIN138_LINK_TOKEN:-0x0000000000000000000000000000000000000000}"
    
    BRIDGE9_OUTPUT=$(forge script script/DeployCCIPWETH9Bridge.s.sol \
        --rpc-url "$RPC_URL" \
        --broadcast \
        --private-key "$PRIVATE_KEY" 2>&1 || true)
    
    BRIDGE9_ADDRESS=$(echo "$BRIDGE9_OUTPUT" | grep -E "CCIPWETH9Bridge deployed at:|deployed at:" | tail -1 | sed 's/.*at: //' | awk '{print $1}' | tr -d '\n' || echo "")
    
    if [ -n "$BRIDGE9_ADDRESS" ] && [ "$BRIDGE9_ADDRESS" != "" ]; then
        WETH9_BRIDGE="$BRIDGE9_ADDRESS"
        log_success "✅ CCIPWETH9Bridge deployed at: $WETH9_BRIDGE"
        
        # Update .env
        if grep -q "^CCIPWETH9_BRIDGE_CHAIN138=" "$PROJECT_ROOT/.env" 2>/dev/null; then
            sed -i.bak "s|^CCIPWETH9_BRIDGE_CHAIN138=.*|CCIPWETH9_BRIDGE_CHAIN138=$WETH9_BRIDGE|" "$PROJECT_ROOT/.env"
        else
            echo "CCIPWETH9_BRIDGE_CHAIN138=$WETH9_BRIDGE" >> "$PROJECT_ROOT/.env"
        fi
    else
        log_error "❌ Failed to deploy CCIPWETH9Bridge"
        exit 1
    fi
else
    log_success "✅ CCIPWETH9Bridge already deployed: $WETH9_BRIDGE"
fi

# Step 4: Deploy CCIPWETH10Bridge
log_info "Step 4: Deploying CCIPWETH10Bridge..."
WETH10_BRIDGE="${CCIPWETH10_BRIDGE_CHAIN138:-}"

if [ -z "$WETH10_BRIDGE" ] || [ "$WETH10_BRIDGE" = "" ]; then
    log_info "Deploying CCIPWETH10Bridge..."
    
    export CCIP_ROUTER="$CCIP_ROUTER"
    export CCIP_FEE_TOKEN="${CCIP_CHAIN138_LINK_TOKEN:-0x0000000000000000000000000000000000000000}"
    
    BRIDGE10_OUTPUT=$(forge script script/DeployCCIPWETH10Bridge.s.sol \
        --rpc-url "$RPC_URL" \
        --broadcast \
        --private-key "$PRIVATE_KEY" 2>&1 || true)
    
    BRIDGE10_ADDRESS=$(echo "$BRIDGE10_OUTPUT" | grep -E "CCIPWETH10Bridge deployed at:|deployed at:" | tail -1 | sed 's/.*at: //' | awk '{print $1}' | tr -d '\n' || echo "")
    
    if [ -n "$BRIDGE10_ADDRESS" ] && [ "$BRIDGE10_ADDRESS" != "" ]; then
        WETH10_BRIDGE="$BRIDGE10_ADDRESS"
        log_success "✅ CCIPWETH10Bridge deployed at: $WETH10_BRIDGE"
        
        # Update .env
        if grep -q "^CCIPWETH10_BRIDGE_CHAIN138=" "$PROJECT_ROOT/.env" 2>/dev/null; then
            sed -i.bak "s|^CCIPWETH10_BRIDGE_CHAIN138=.*|CCIPWETH10_BRIDGE_CHAIN138=$WETH10_BRIDGE|" "$PROJECT_ROOT/.env"
        else
            echo "CCIPWETH10_BRIDGE_CHAIN138=$WETH10_BRIDGE" >> "$PROJECT_ROOT/.env"
        fi
    else
        log_error "❌ Failed to deploy CCIPWETH10Bridge"
        exit 1
    fi
else
    log_success "✅ CCIPWETH10Bridge already deployed: $WETH10_BRIDGE"
fi

# Step 5: Verify Deployment
log_info "Step 5: Verifying deployment..."
bash "$PROJECT_ROOT/scripts/deployment/verify-ccip-deployment.sh" || log_warn "⚠️  Verification had issues"

# Step 6: Summary
echo ""
log_success "=== Deployment Summary ==="
echo "CCIP Router: $CCIP_ROUTER"
echo "CCIPWETH9Bridge: $WETH9_BRIDGE"
echo "CCIPWETH10Bridge: $WETH10_BRIDGE"
echo ""
echo "Next steps:"
echo "1. Configure bridge destinations:"
echo "   ./scripts/deployment/configure-weth9-bridge.sh"
echo "   ./scripts/deployment/configure-weth10-bridge.sh"
echo "2. Verify on explorer"
echo "3. Test cross-chain transfers"
echo "4. Update documentation with deployed addresses"

log_success "✅ CCIP deployment complete!"

