#!/usr/bin/env bash
# Verify Fee Calculation
# Task 64: Create Fee Calculation Verification Script
# Usage: ./verify-fee-calculation.sh [amount_eth] [destination_selector]

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}"
CCIP_ROUTER="0x42DAb7b888Dd382bD5Adcf9E038dBF1fD03b4817"
LINK_TOKEN="0x514910771AF9Ca656af840dff83E8264EcF986CA"

# Default values
AMOUNT_ETH="${1:-0.001}"
DEST_SELECTOR="${2:-$(ccip_destination_selector_by_name "Ethereum Mainnet")}"  # Ethereum Mainnet

log_info "========================================="
log_info "Fee Calculation Verification"
log_info "========================================="
log_info ""
log_info "Router Address: $CCIP_ROUTER"
log_info "Amount: $AMOUNT_ETH ETH"
log_info "Destination Selector: $DEST_SELECTOR"
log_info "RPC URL: $RPC_URL"
log_info ""

# Convert amount to wei
AMOUNT_WEI=$(cast --to-wei "$AMOUNT_ETH" ether 2>/dev/null || echo "")

if [ -z "$AMOUNT_WEI" ]; then
    log_error "Failed to convert amount to wei"
    exit 1
fi

log_info "Amount in Wei: $AMOUNT_WEI"
log_info ""

# Step 1: Try to get fee using Router.getFee()
log_info "Step 1: Attempting to get fee from Router..."
log_info "  Method: Router.getFee(destinationChainSelector, data)"

# Prepare message data (empty for token transfer)
MESSAGE_DATA="0x"

# Try to call getFee
FEE_RESULT=$(cast call "$CCIP_ROUTER" "getFee(uint64,bytes)" "$DEST_SELECTOR" "$MESSAGE_DATA" --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
        FEE_ETH=$(cast --from-wei "$FEE_WEI" ether 2>/dev/null || echo "")
        if [ -n "$FEE_ETH" ]; then
            log_success "  Fee (Wei): $FEE_WEI"
            log_success "  Fee (ETH): $FEE_ETH"
        else
            log_success "  Fee (Wei): $FEE_WEI"
        fi
    else
        log_warn "  getFee() returned: $FEE_RESULT (could not parse)"
    fi
else
    log_warn "  getFee() function not available or returned empty"
fi

# Step 2: Try to get fee token
log_info ""
log_info "Step 2: Checking fee token configuration..."

FEE_TOKEN=$(cast call "$CCIP_ROUTER" "getFeeToken()" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
if [ -n "$FEE_TOKEN" ] && [ "$FEE_TOKEN" != "0x" ]; then
    FEE_TOKEN_CLEAN=$(echo "$FEE_TOKEN" | grep -oE "^0x[0-9a-fA-F]{40}$" | head -1 || echo "")
    if [ -n "$FEE_TOKEN_CLEAN" ]; then
        if [ "$(echo "$FEE_TOKEN_CLEAN" | tr '[:upper:]' '[:lower:]')" = "$(echo "$LINK_TOKEN" | tr '[:upper:]' '[:lower:]')" ]; then
            log_success "  Fee Token: $FEE_TOKEN_CLEAN (LINK - matches expected)"
        else
            log_info "  Fee Token: $FEE_TOKEN_CLEAN"
        fi
    else
        log_warn "  getFeeToken() returned invalid address"
    fi
else
    log_warn "  getFeeToken() function not available"
fi

# Step 3: Check LINK token balance (if fee token is LINK)
if [ -n "$FEE_TOKEN_CLEAN" ] && [ "$(echo "$FEE_TOKEN_CLEAN" | tr '[:upper:]' '[:lower:]')" = "$(echo "$LINK_TOKEN" | tr '[:upper:]' '[:lower:]')" ]; then
    log_info ""
    log_info "Step 3: Checking LINK token availability..."
    log_info "  Note: LINK balance check requires account address"
    log_info "  To check balance: cast balance <address> --rpc-url $RPC_URL"
fi

# Step 4: Test different amounts
log_info ""
log_info "Step 4: Testing fee calculation for different amounts..."

TEST_AMOUNTS=("0.0001" "0.001" "0.01" "0.1" "1.0")

for TEST_AMOUNT in "${TEST_AMOUNTS[@]}"; do
    TEST_WEI=$(cast --to-wei "$TEST_AMOUNT" ether 2>/dev/null || echo "")
    if [ -n "$TEST_WEI" ]; then
        TEST_FEE=$(cast call "$CCIP_ROUTER" "getFee(uint64,bytes)" "$DEST_SELECTOR" "$MESSAGE_DATA" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
        if [ -n "$TEST_FEE" ] && [ "$TEST_FEE" != "0x" ]; then
            TEST_FEE_WEI=$(echo "$TEST_FEE" | grep -oE "[0-9]+" | head -1 || echo "")
            if [ -n "$TEST_FEE_WEI" ]; then
                TEST_FEE_ETH=$(cast --from-wei "$TEST_FEE_WEI" ether 2>/dev/null || echo "")
                log_info "  Amount: $TEST_AMOUNT ETH -> Fee: ${TEST_FEE_ETH:-$TEST_FEE_WEI wei}"
            fi
        fi
    fi
done

# Summary
log_info ""
log_info "========================================="
log_info "Verification Summary"
log_info "========================================="
if [ -n "$FEE_RESULT" ] && [ "$FEE_RESULT" != "0x" ]; then
    log_success "✓ Fee calculation is working"
else
    log_warn "⚠ Fee calculation may not be accessible"
    log_info "  This could indicate:"
    log_info "    1. Router contract doesn't expose getFee() function"
    log_info "    2. Fee calculation requires different parameters"
    log_info "    3. Fee calculation is handled by a separate contract"
fi
log_info ""
