#!/usr/bin/env bash
# Complete CCIP Setup Workflow
# Automates the entire CCIP setup process using PRIVATE_KEY from .env
# Usage: ./complete-ccip-setup.sh

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
source "$PROJECT_ROOT/scripts/lib/address-inventory.sh"
source "$PROJECT_ROOT/scripts/lib/ccip-destinations.sh"

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
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"; }
log_step() { echo -e "${CYAN}[STEP]${NC} $1"; }

load_explorer_runtime_env

log_info "========================================="
log_info "Complete CCIP Setup Workflow"
log_info "========================================="
log_info ""
log_info "This script will:"
log_info "  1. Run pre-flight checks"
log_info "  2. Configure all bridge destinations"
log_info "  3. Verify configuration"
log_info "  4. Generate status report"
log_info ""

# Step 1: Pre-flight checks
log_step "Step 1: Pre-Flight Checks"
log_info ""

if ! "$SCRIPT_DIR/pre-flight-check.sh"; then
    log_error "Pre-flight checks failed"
    log_info "Fix the issues above and try again"
    exit 1
fi

log_info ""
log_success "Pre-flight checks passed"
log_info ""

# Step 2: Configure all destinations
log_step "Step 2: Configure All Bridge Destinations"
log_info ""

if [ -z "${PRIVATE_KEY:-}" ]; then
    log_error "PRIVATE_KEY not available in effective environment"
    exit 1
fi

log_info "Using PRIVATE_KEY from effective environment"
log_info ""

if ! "$SCRIPT_DIR/configure-all-destinations-auto.sh"; then
    log_warn "Configuration had some failures"
    log_info "Review output above for details"
fi

log_info ""

# Step 3: Verify configuration
log_step "Step 3: Verify Configuration"
log_info ""

log_info "Running comprehensive verification..."
"$SCRIPT_DIR/verify-complete-ccip-setup.sh"

log_info ""

# Step 4: Generate status report
log_step "Step 4: Generate Status Report"
log_info ""

REPORT_FILE="docs/CCIP_SETUP_COMPLETE_$(date +%Y%m%d_%H%M%S).md"
"$SCRIPT_DIR/generate-ccip-status-report.sh" "$REPORT_FILE"

log_info ""

# Step 5: Final summary
log_step "Step 5: Final Summary"
log_info ""

log_info "========================================="
log_info "Setup Complete"
log_info "========================================="
log_info ""

# Check final configuration status
WETH9_CONFIGURED=0
WETH10_CONFIGURED=0

RPC_URL="${RPC_URL_138:-http://192.168.11.250:8545}"
WETH9_BRIDGE="$(resolve_address_value CCIPWETH9_BRIDGE CCIPWETH9_BRIDGE 0x971cD9D156f193df8051E48043C476e53ECd4693)"
WETH10_BRIDGE="$(resolve_address_value CCIPWETH10_BRIDGE CCIPWETH10_BRIDGE 0xe0E93247376aa097dB308B92e6Ba36bA015535D0)"

TOTAL_DESTINATIONS=$(ccip_destination_count)

while IFS=$'\t' read -r _chain_name SELECTOR _weth9 _weth10 _rpc_url; do
    
    DEST_WETH9=$(cast call "$WETH9_BRIDGE" "destinations(uint64)" "$SELECTOR" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
    DEST_WETH9_CLEAN=$(echo "$DEST_WETH9" | grep -oE "^0x[0-9a-fA-F]{40}$" | head -1 || echo "")
    if [ -n "$DEST_WETH9_CLEAN" ] && ! echo "$DEST_WETH9_CLEAN" | grep -qE "^0x0+$"; then
        ((WETH9_CONFIGURED++)) || true
    fi
    
    DEST_WETH10=$(cast call "$WETH10_BRIDGE" "destinations(uint64)" "$SELECTOR" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
    DEST_WETH10_CLEAN=$(echo "$DEST_WETH10" | grep -oE "^0x[0-9a-fA-F]{40}$" | head -1 || echo "")
    if [ -n "$DEST_WETH10_CLEAN" ] && ! echo "$DEST_WETH10_CLEAN" | grep -qE "^0x0+$"; then
        ((WETH10_CONFIGURED++)) || true
    fi
done < <(ccip_destination_rows)

log_info "Final Configuration Status:"
log_info "  WETH9 Bridge: $WETH9_CONFIGURED/$TOTAL_DESTINATIONS destinations"
log_info "  WETH10 Bridge: $WETH10_CONFIGURED/$TOTAL_DESTINATIONS destinations"
log_info ""

if [ "$WETH9_CONFIGURED" -eq "$TOTAL_DESTINATIONS" ] && [ "$WETH10_CONFIGURED" -eq "$TOTAL_DESTINATIONS" ]; then
    log_success "✓ All destinations configured successfully!"
    log_info ""
    log_info "Next steps:"
    log_info "  1. Test bridge operations:"
    log_info "     ./scripts/test-end-to-end-bridge.sh 0.001"
    log_info ""
    log_info "  2. Bridge tokens:"
    log_info "     ./scripts/wrap-and-bridge-to-ethereum.sh 0.001"
    log_info ""
    log_info "  3. Monitor system:"
    log_info "     ./scripts/ccip-health-check.sh"
    exit 0
elif [ $WETH9_CONFIGURED -gt 0 ] || [ $WETH10_CONFIGURED -gt 0 ]; then
    log_warn "⚠ Partial configuration complete"
    log_info "  Re-run this script to configure remaining destinations"
    exit 0
else
    log_error "✗ Configuration failed"
    log_info "  Review output above for details"
    exit 1
fi
