#!/usr/bin/env bash
# Check Fee Requirements for Bridge Operations
# Validates LINK balance, ETH balance, and fee calculations
# Usage: ./check-fee-requirements.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/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'
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_explorer_runtime_env

# Configuration
RPC_URL="${RPC_URL_138:-http://192.168.11.250:8545}"
AMOUNT_ETH="${1:-1.0}"
AMOUNT_WEI=$(cast --to-wei "$AMOUNT_ETH" ether 2>/dev/null || echo "")

if [ -z "$AMOUNT_WEI" ]; then
    log_error "Invalid amount: $AMOUNT_ETH"
    exit 1
fi

# Contract addresses
LINK_TOKEN="$(resolve_address_value LINK_TOKEN LINK_TOKEN 0x326C977E6efc84E512bB9C30f76E30c160eD06FB)"
WETH9_BRIDGE="$(resolve_address_value CCIPWETH9_BRIDGE CCIPWETH9_BRIDGE 0x971cD9D156f193df8051E48043C476e53ECd4693)"
WETH10_BRIDGE="$(resolve_address_value CCIPWETH10_BRIDGE CCIPWETH10_BRIDGE 0xe0E93247376aa097dB308B92e6Ba36bA015535D0)"

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

ACCOUNT=$(cast wallet address "$PRIVATE_KEY" 2>/dev/null || echo "")
if [ -z "$ACCOUNT" ]; then
    log_error "Could not derive address from PRIVATE_KEY"
    exit 1
fi

log_info "========================================="
log_info "Fee Requirements Check"
log_info "========================================="
log_info ""
log_info "Account: $ACCOUNT"
log_info "Amount: $AMOUNT_ETH ETH"
log_info ""

PASSED=0
FAILED=0
WARNINGS=0

# Check 1: ETH Balance
log_info "1. ETH Balance Check"
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 "0")
REQUIRED_ETH="0.1"  # Minimum for gas

if (( $(echo "$ETH_BALANCE_ETH >= $REQUIRED_ETH" | bc -l 2>/dev/null || echo 0) )); then
    log_success "ETH balance: $ETH_BALANCE_ETH ETH (sufficient)"
    ((PASSED++)) || true
else
    log_error "ETH balance: $ETH_BALANCE_ETH ETH (insufficient, need $REQUIRED_ETH ETH)"
    ((FAILED++)) || true
fi

# Check 2: LINK Token Contract
log_info ""
log_info "2. LINK Token Contract Check"
LINK_CODE=$(cast code "$LINK_TOKEN" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
if [ -z "$LINK_CODE" ] || [ "$LINK_CODE" = "0x" ]; then
    log_error "LINK token contract not deployed or empty"
    log_warn "  Address: $LINK_TOKEN"
    log_warn "  Action: Deploy LINK token contract"
    ((FAILED++)) || true
else
    log_success "LINK token contract deployed"
    ((PASSED++)) || true
fi

# Check 3: LINK Balance (Account)
log_info ""
log_info "3. LINK Balance Check (Account)"
LINK_BALANCE="0"
if [ -n "$LINK_CODE" ] && [ "$LINK_CODE" != "0x" ]; then
    LINK_BALANCE=$(cast call "$LINK_TOKEN" "balanceOf(address)" "$ACCOUNT" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
    LINK_BALANCE_ETH=$(cast --from-wei "$LINK_BALANCE" ether 2>/dev/null || echo "0")
    
    if [ "$LINK_BALANCE" != "0" ] && [ "$LINK_BALANCE" != "0x" ]; then
        log_success "LINK balance: $LINK_BALANCE_ETH LINK"
        ((PASSED++)) || true
    else
        log_warn "LINK balance: 0 LINK"
        log_warn "  Action: Transfer LINK tokens to account"
        ((WARNINGS++)) || true
    fi
else
    log_warn "Cannot check LINK balance (contract not deployed)"
    ((WARNINGS++)) || true
fi

# Check 4: LINK Balance (Bridge Contracts)
log_info ""
log_info "4. LINK Balance Check (Bridge Contracts)"
if [ -n "$LINK_CODE" ] && [ "$LINK_CODE" != "0x" ]; then
    WETH9_LINK=$(cast call "$LINK_TOKEN" "balanceOf(address)" "$WETH9_BRIDGE" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
    WETH10_LINK=$(cast call "$LINK_TOKEN" "balanceOf(address)" "$WETH10_BRIDGE" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
    
    WETH9_LINK_ETH=$(cast --from-wei "$WETH9_LINK" ether 2>/dev/null || echo "0")
    WETH10_LINK_ETH=$(cast --from-wei "$WETH10_LINK" ether 2>/dev/null || echo "0")
    
    REQUIRED_LINK="1.0"  # Minimum LINK for fees
    
    if (( $(echo "$WETH9_LINK_ETH >= $REQUIRED_LINK" | bc -l 2>/dev/null || echo 0) )); then
        log_success "WETH9 Bridge LINK: $WETH9_LINK_ETH LINK"
        ((PASSED++)) || true
    else
        log_warn "WETH9 Bridge LINK: $WETH9_LINK_ETH LINK (need $REQUIRED_LINK LINK)"
        log_warn "  Action: Transfer LINK to WETH9 Bridge"
        ((WARNINGS++)) || true
    fi
    
    if (( $(echo "$WETH10_LINK_ETH >= $REQUIRED_LINK" | bc -l 2>/dev/null || echo 0) )); then
        log_success "WETH10 Bridge LINK: $WETH10_LINK_ETH LINK"
        ((PASSED++)) || true
    else
        log_warn "WETH10 Bridge LINK: $WETH10_LINK_ETH LINK (need $REQUIRED_LINK LINK)"
        log_warn "  Action: Transfer LINK to WETH10 Bridge"
        ((WARNINGS++)) || true
    fi
else
    log_warn "Cannot check bridge LINK balance (contract not deployed)"
    ((WARNINGS++)) || true
fi

# Check 5: Fee Calculation
log_info ""
log_info "5. Fee Calculation Check"
FEE_CALCULATED=0
for CHAIN_NAME in BSC Ethereum; do
    SELECTOR="$(ccip_destination_field_by_name "$CHAIN_NAME" selector)"
    FEE=$(cast call "$WETH9_BRIDGE" "calculateFee(uint64,uint256)" "$SELECTOR" "$AMOUNT_WEI" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
    
    if [ "$FEE" != "0" ] && [ -n "$FEE" ]; then
        FEE_ETH=$(cast --from-wei "$FEE" ether 2>/dev/null || echo "0")
        log_success "$CHAIN_NAME fee: $FEE_ETH ETH"
        FEE_CALCULATED=1
    fi
done

if [ $FEE_CALCULATED -eq 1 ]; then
    ((PASSED++)) || true
else
    log_warn "Fee calculation failed or returned 0"
    log_warn "  This may indicate LINK token issues"
    ((WARNINGS++)) || true
fi

# Summary
log_info ""
log_info "========================================="
log_info "Summary"
log_info "========================================="
log_info ""
log_success "Passed: $PASSED"
log_warn "Warnings: $WARNINGS"
log_error "Failed: $FAILED"
log_info ""

if [ $FAILED -eq 0 ]; then
    if [ $WARNINGS -eq 0 ]; then
        log_success "✓ All fee requirements met!"
        exit 0
    else
        log_warn "⚠ Requirements met with warnings"
        exit 0
    fi
else
    log_error "✗ Some requirements not met"
    log_info ""
    log_info "Actions Required:"
    if [ -z "$LINK_CODE" ] || [ "$LINK_CODE" = "0x" ]; then
        log_info "  1. Deploy LINK token contract"
    fi
    if [ "$LINK_BALANCE" = "0" ] || [ "$LINK_BALANCE" = "0x" ]; then
        log_info "  2. Transfer LINK tokens to account"
    fi
    exit 1
fi
