#!/usr/bin/env bash

# Execute Full Bidirectional Bridge Configuration
# This script attempts to configure both directions using available selector information

set -e

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

# 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"; }

log_info "=== Full Bidirectional Bridge Configuration ==="
log_info ""

# Load environment if available
if [ -f "$PROJECT_ROOT/.env" ]; then
    source "$PROJECT_ROOT/.env" 2>/dev/null || true
fi

# Step 1: Configure ChainID 138 → Mainnet (always possible)
log_info "Step 1: Configuring ChainID 138 → Mainnet..."
./scripts/configuration/configure-chain138-to-mainnet.sh

log_info ""
log_info "---"

# Step 2: Try to configure Mainnet → ChainID 138 (if selector available)
log_info "Step 2: Attempting Mainnet → ChainID 138 configuration..."

# Get selector from networks.json if not in env
if [ -z "$CHAIN138_SELECTOR" ] && [ -f "$PROJECT_ROOT/networks.json" ]; then
    CHAIN138_SELECTOR=$(python3 -c "import json; data=json.load(open('$PROJECT_ROOT/networks.json')); print(data['networks']['138']['chainSelector'])" 2>/dev/null || echo "")
    if [ -n "$CHAIN138_SELECTOR" ]; then
        log_info "Using ChainID 138 selector from networks.json: $CHAIN138_SELECTOR"
        export CHAIN138_SELECTOR
    fi
fi

if [ -n "$CHAIN138_SELECTOR" ]; then
    ./scripts/configuration/configure-mainnet-to-chain138.sh
    log_success "✓ Bidirectional configuration complete!"
else
    log_warn "⚠ ChainID 138 selector not available - only ChainID 138 → Mainnet configured"
    log_info "To complete bidirectional setup:"
    log_info "1. Determine ChainID 138 selector"
    log_info "2. Set in .env: CHAIN138_SELECTOR=<selector>"
    log_info "3. Run: ./scripts/configuration/configure-mainnet-to-chain138.sh"
fi

log_info ""
log_info "---"

# Step 3: Verify configuration
log_info "Step 3: Verifying configuration..."
./scripts/configuration/verify-bridge-configuration.sh

log_info ""
log_success "=== Configuration Process Complete ==="
