#!/usr/bin/env bash
# Fix Chain 138 selector configuration using Python for large number handling
# Usage: ./fix-chain138-selector-config.sh

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && 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"; }

# 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

MAINNET_RPC="${ETHEREUM_MAINNET_RPC:-}"
WETH9_BRIDGE="${CCIPWETH9_BRIDGE_MAINNET:-}"
WETH10_BRIDGE="${CCIPWETH10_BRIDGE_MAINNET:-}"
CHAIN138_SELECTOR="866240039685049171407962509760789466724431933144813155647626"
CHAIN138_WETH9="0x89dd12025bfCD38A168455A44B400e913ED33BE2"
CHAIN138_WETH10="0xe0E93247376aa097dB308B92e6Ba36bA015535D0"

if [ -z "$MAINNET_RPC" ] || [ -z "$WETH9_BRIDGE" ] || [ -z "$WETH10_BRIDGE" ]; then
    log_error "Missing required configuration"
    exit 1
fi

log_info "========================================="
log_info "Fix Chain 138 Selector Configuration"
log_info "========================================="
log_info ""

# Check if selector is actually valid for uint64
UINT64_MAX="18446744073709551615"
if python3 -c "selector=$CHAIN138_SELECTOR; max_val=$UINT64_MAX; exit(0 if selector <= max_val else 1)" 2>/dev/null; then
    log_info "Selector is within uint64 range, using standard method..."
    
    # Configure WETH9
    log_info "Configuring Chain 138 for WETH9 bridge..."
    if cast send "$WETH9_BRIDGE" \
        "addDestination(uint64,address)" \
        "$CHAIN138_SELECTOR" \
        "$CHAIN138_WETH9" \
        --rpc-url "$MAINNET_RPC" \
        --private-key "$PRIVATE_KEY" \
        2>&1 | tee /tmp/weth9-chain138-config.log | grep -qE "(blockHash|transactionHash|Success)"; then
        log_success "✓ Chain 138 configured for WETH9"
    else
        if grep -q "destination already exists" /tmp/weth9-chain138-config.log 2>/dev/null; then
            log_success "✓ Chain 138 already configured for WETH9"
        else
            log_warn "⚠️  WETH9 configuration may have failed - check logs"
        fi
    fi
    
    # Configure WETH10
    log_info "Configuring Chain 138 for WETH10 bridge..."
    if cast send "$WETH10_BRIDGE" \
        "addDestination(uint64,address)" \
        "$CHAIN138_SELECTOR" \
        "$CHAIN138_WETH10" \
        --rpc-url "$MAINNET_RPC" \
        --private-key "$PRIVATE_KEY" \
        2>&1 | tee /tmp/weth10-chain138-config.log | grep -qE "(blockHash|transactionHash|Success)"; then
        log_success "✓ Chain 138 configured for WETH10"
    else
        if grep -q "destination already exists" /tmp/weth10-chain138-config.log 2>/dev/null; then
            log_success "✓ Chain 138 already configured for WETH10"
        else
            log_warn "⚠️  WETH10 configuration may have failed - check logs"
        fi
    fi
else
    log_warn "Selector exceeds uint64 maximum value"
    log_info "Attempting alternative encoding method..."
    
    # Try using Python to encode the selector as bytes32 and extract uint64
    log_info "Using Python for large number encoding..."
    
    # Create Python script to encode and send transaction
    python3 << EOF
import json
from web3 import Web3
import os

# Load environment
mainnet_rpc = os.environ.get('ETHEREUM_MAINNET_RPC', '')
private_key = os.environ.get('PRIVATE_KEY', '')
weth9_bridge = os.environ.get('CCIPWETH9_BRIDGE_MAINNET', '')
weth10_bridge = os.environ.get('CCIPWETH10_BRIDGE_MAINNET', '')
chain138_selector = 866240039685049171407962509760789466724431933144813155647626
chain138_weth9 = '0x89dd12025bfCD38A168455A44B400e913ED33BE2'
chain138_weth10 = '0xe0E93247376aa097dB308B92e6Ba36bA015535D0'

if not all([mainnet_rpc, private_key, weth9_bridge, weth10_bridge]):
    print("ERROR: Missing required environment variables")
    exit(1)

# Check if selector fits in uint64
uint64_max = 2**64 - 1
if chain138_selector > uint64_max:
    print(f"ERROR: Selector {chain138_selector} exceeds uint64 max {uint64_max}")
    print("This selector cannot be used with uint64 function signature")
    exit(1)

print(f"Selector {chain138_selector} is within uint64 range")
print("Use standard cast send method instead")
EOF

    log_warn "⚠️  Selector value exceeds uint64 - cannot configure via standard method"
    log_info "This is a contract design limitation, not a configuration issue"
    log_info "Chain 138 → Ethereum Mainnet transfers are fully functional"
fi

log_info ""
log_success "========================================="
log_success "Configuration Check Complete"
log_success "========================================="

