#!/usr/bin/env bash
# End-to-End Bridge Test
# Task 119: Create End-to-End Test Script
# Usage: ./test-end-to-end-bridge.sh [amount_eth]

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
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'
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 .env exists
if [ -f "$PROJECT_ROOT/.env" ]; then
    source "$PROJECT_ROOT/.env"
elif [ -f "$PROJECT_ROOT/../.env" ]; then
    source "$PROJECT_ROOT/../.env"
fi

# Configuration
RPC_URL="${RPC_URL_138:-http://192.168.11.250:8545}"
AMOUNT_ETH="${1:-0.001}"
DESTINATION_SELECTOR="${DESTINATION_SELECTOR:-$(ccip_destination_selector_by_name "Ethereum Mainnet")}"  # Ethereum Mainnet

log_info "========================================="
log_info "End-to-End Bridge Test"
log_info "========================================="
log_info ""
log_info "Amount: $AMOUNT_ETH ETH"
log_info "Destination: Ethereum Mainnet ($DESTINATION_SELECTOR)"
log_info "RPC URL: $RPC_URL"
log_info ""

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

# Check RPC connectivity
log_info "  Checking RPC connectivity..."
BLOCK_NUMBER=$(cast block-number --rpc-url "$RPC_URL" 2>/dev/null || echo "")
if [ -z "$BLOCK_NUMBER" ]; then
    log_error "  RPC not accessible"
    exit 1
fi
log_success "  RPC accessible (block: $BLOCK_NUMBER)"

# Check bridge configuration
log_info "  Checking bridge configuration..."
WETH9_BRIDGE="0xcacfd227A040002e49e2e01626363071324f820a"
DEST=$(cast call "$WETH9_BRIDGE" "destinations(uint64)" "$DESTINATION_SELECTOR" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
DEST_CLEAN=$(echo "$DEST" | grep -oE "^0x[0-9a-fA-F]{40}$" | head -1 || echo "")
if [ -z "$DEST_CLEAN" ] || echo "$DEST_CLEAN" | grep -qE "^0x0+$"; then
    log_error "  Ethereum Mainnet destination not configured"
    log_info "  Run: ./scripts/fix-bridge-errors.sh <private_key> <bridge_address>"
    exit 1
fi
log_success "  Bridge destination configured: $DEST_CLEAN"

# Step 2: Verify token mechanism
log_info ""
log_info "Step 2: Verify Token Mechanism"
log_info ""

WETH9="0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"
WETH9_BALANCE=$(cast balance "$WETH9" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
WETH9_SUPPLY=$(cast call "$WETH9" "totalSupply()" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
if [ "$WETH9_BALANCE" = "$WETH9_SUPPLY" ]; then
    log_success "  WETH9 1:1 ratio verified"
else
    log_warn "  WETH9 1:1 ratio: Balance=$WETH9_BALANCE, Supply=$WETH9_SUPPLY"
fi

# Step 3: Check account balance
log_info ""
log_info "Step 3: Check Account Balance"
log_info ""

if [ -z "${PRIVATE_KEY:-}" ]; then
    log_warn "  Private key not set, skipping balance check"
    log_info "  Set PRIVATE_KEY in .env to test with actual transactions"
else
    ACCOUNT=$(cast wallet address "$PRIVATE_KEY" 2>/dev/null || echo "")
    if [ -n "$ACCOUNT" ]; then
        ETH_BALANCE=$(cast balance "$ACCOUNT" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
        ETH_BALANCE_ETH=$(cast --from-wei "$ETH_BALANCE" ether 2>/dev/null || echo "")
        log_info "  Account: $ACCOUNT"
        log_info "  ETH Balance: ${ETH_BALANCE_ETH:-$ETH_BALANCE} ETH"
        
        AMOUNT_WEI=$(cast --to-wei "$AMOUNT_ETH" ether 2>/dev/null || echo "")
        if [ -n "$AMOUNT_WEI" ] && [ "$ETH_BALANCE" -lt "$AMOUNT_WEI" ]; then
            log_error "  Insufficient balance for test"
            exit 1
        fi
        log_success "  Sufficient balance for test"
    fi
fi

# Step 4: Verify fee calculation
log_info ""
log_info "Step 4: Verify Fee Calculation"
log_info ""

CCIP_ROUTER="0x42DAb7b888Dd382bD5Adcf9E038dBF1fD03b4817"
FEE_RESULT=$(cast call "$CCIP_ROUTER" "getFee(uint64,bytes)" "$DESTINATION_SELECTOR" "0x" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
if [ -n "$FEE_RESULT" ] && [ "$FEE_RESULT" != "0x" ]; then
    FEE_WEI=$(echo "$FEE_RESULT" | grep -oE "[0-9]+" | head -1 || echo "")
    if [ -n "$FEE_WEI" ]; then
        log_success "  Fee calculation working: $FEE_WEI wei"
    else
        log_warn "  Fee calculation returned: $FEE_RESULT"
    fi
else
    log_warn "  Fee calculation not accessible"
fi

# Step 5: Summary
log_info ""
log_info "========================================="
log_info "Test Summary"
log_info "========================================="
log_info ""

if [ -z "${PRIVATE_KEY:-}" ]; then
    log_warn "⚠ Private key not set - dry run only"
    log_info ""
    log_info "To run actual test:"
    log_info "  1. Set PRIVATE_KEY in .env"
    log_info "  2. Run: ./scripts/wrap-and-bridge-to-ethereum.sh $AMOUNT_ETH"
else
    log_info "Ready for end-to-end test"
    log_info ""
    log_info "To execute test:"
    log_info "  ./scripts/wrap-and-bridge-to-ethereum.sh $AMOUNT_ETH"
fi

log_info ""
log_success "✓ Pre-flight checks completed"
log_info ""
