#!/usr/bin/env bash

# Verify LINK Token Requirements for ChainID 138
# Comprehensive check of LINK token availability and requirements

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'
CYAN='\033[0;36m'
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
if [ -f "$PROJECT_ROOT/.env" ]; then
    source "$PROJECT_ROOT/.env" 2>/dev/null || true
fi

if [ -z "$PRIVATE_KEY" ]; then
    log_error "PRIVATE_KEY not set in .env"
    exit 1
fi

CHAIN138_RPC="${RPC_URL_138:-http://192.168.11.211:8545}"
EXPECTED_LINK="0x514910771AF9Ca656af840dff83E8264EcF986CA"
WALLET_ADDRESS=$(cast wallet address --private-key "$PRIVATE_KEY")
CCIP_ROUTER="${CCIP_ROUTER_138:-0x42DAb7b888Dd382bD5Adcf9E038dBF1fD03b4817}"

log_info "=== LINK Token Requirements Verification (ChainID 138) ==="
log_info "Wallet: $WALLET_ADDRESS"
log_info ""

# Check 1: LINK Token Contract Existence
log_info "1. Checking LINK token contract..."
LINK_CODE=$(cast code "$EXPECTED_LINK" --rpc-url "$CHAIN138_RPC" 2>/dev/null || echo "")
if [ -z "$LINK_CODE" ] || [ "${#LINK_CODE}" -lt 10 ]; then
    log_error "   ❌ LINK token contract not found at $EXPECTED_LINK"
    LINK_EXISTS=false
else
    log_success "   ✓ LINK token contract exists"
    LINK_EXISTS=true
fi

# Check 2: CCIP Router Fee Token
log_info ""
log_info "2. Checking CCIP Router fee token..."
FEE_TOKEN=$(cast call "$CCIP_ROUTER" "feeToken()(address)" --rpc-url "$CHAIN138_RPC" 2>&1 || echo "ERROR")
if [[ "$FEE_TOKEN" == *"ERROR"* ]] || [[ "$FEE_TOKEN" == *"error"* ]]; then
    log_warn "   ⚠ Could not query fee token: $FEE_TOKEN"
else
    FEE_TOKEN_CLEAN=$(echo "$FEE_TOKEN" | tr -d '\n' | cast to-address 2>/dev/null || echo "$FEE_TOKEN")
    log_info "   CCIP Router fee token: $FEE_TOKEN_CLEAN"
    
    if [ "$FEE_TOKEN_CLEAN" = "0x0000000000000000000000000000000000000000" ]; then
        log_info "   Router uses native ETH for fees (address(0))"
        NATIVE_FEES=true
    else
        NATIVE_FEES=false
    fi
fi

# Check 3: Wallet LINK Balance (if LINK exists)
if [ "$LINK_EXISTS" = true ]; then
    log_info ""
    log_info "3. Checking wallet LINK balance..."
    BALANCE=$(cast call "$EXPECTED_LINK" "balanceOf(address)(uint256)" "$WALLET_ADDRESS" --rpc-url "$CHAIN138_RPC" 2>&1 || echo "ERROR")
    
    if [[ "$BALANCE" == *"ERROR"* ]]; then
        log_warn "   ⚠ Could not check balance: $BALANCE"
    else
        BALANCE_LINK=$(echo "$BALANCE" | cast --to-unit wei ether 2>/dev/null || echo "0")
        log_info "   LINK Balance: $BALANCE_LINK LINK"
        
        if (( $(echo "$BALANCE_LINK >= 1.0" | bc -l 2>/dev/null || echo "0") )); then
            log_success "   ✓ Sufficient balance (>= 1 LINK)"
        else
            log_warn "   ⚠ Low balance: $BALANCE_LINK LINK (recommended: >= 1 LINK)"
        fi
    fi
else
    log_info ""
    log_warn "3. ⚠ Skipping balance check (LINK contract doesn't exist)"
fi

# Summary
log_info ""
log_info "=== Summary ==="

if [ "$LINK_EXISTS" = false ]; then
    log_error "❌ LINK token contract not deployed on ChainID 138"
    log_info ""
    log_info "Required Actions:"
    log_info "1. Deploy LINK token contract to ChainID 138"
    log_info "2. OR configure CCIP Router to use native ETH fees"
    log_info "3. OR find existing LINK token at different address"
    log_info ""
    log_info "See: docs/deployment/LINK_TOKEN_STATUS_CHAIN138.md"
    exit 1
elif [ "$NATIVE_FEES" = true ]; then
    log_warn "⚠ CCIP Router uses native ETH fees (LINK not required for fees)"
    log_success "✓ System can operate with native ETH fees"
    exit 0
else
    log_success "✓ LINK token exists and configuration looks correct"
    exit 0
fi
