#!/usr/bin/env bash
# Get Comprehensive Funding Report
# Shows balances, prices, and funding requirements
# Usage: ./get-funding-report.sh

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"

# 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"; }
log_header() { echo -e "${CYAN}[HEADER]${NC} $1"; }

load_explorer_runtime_env

# Configuration
RPC_URL="${RPC_URL_138:-http://192.168.11.250:8545}"
LINK_TOKEN="$(resolve_address_value LINK_TOKEN LINK_TOKEN 0x326C977E6efc84E512bB9C30f76E30c160eD06FB)"
WETH9="$(resolve_address_value WETH9_ADDRESS WETH9_ADDRESS 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2)"
WETH10="$(resolve_address_value WETH10_ADDRESS WETH10_ADDRESS 0xf4BB2e28688e89fCcE3c0580D37d36A7672E8A9f)"
WETH9_BRIDGE="$(resolve_address_value CCIPWETH9_BRIDGE CCIPWETH9_BRIDGE 0xcacfd227A040002e49e2e01626363071324f820a)"
WETH10_BRIDGE="$(resolve_address_value CCIPWETH10_BRIDGE CCIPWETH10_BRIDGE 0xe0E93247376aa097dB308B92e6Ba36bA015535D0)"

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

# Get prices (using CoinGecko API)
get_price() {
    local symbol="$1"
    local price=$(curl -s "https://api.coingecko.com/api/v3/simple/price?ids=${symbol}&vs_currencies=usd" 2>/dev/null | grep -oE '"usd":[0-9.]+' | cut -d: -f2 || echo "0")
    echo "$price"
}

log_header "========================================="
log_header "Comprehensive Funding Report"
log_header "========================================="
log_info ""
log_info "Account: $ACCOUNT"
log_info "Network: ChainID 138"
log_info "RPC: $RPC_URL"
log_info ""

# Get prices
log_info "Fetching current prices..."
ETH_PRICE=$(get_price "ethereum")
LINK_PRICE=$(get_price "chainlink")

if [ "$ETH_PRICE" = "0" ] || [ -z "$ETH_PRICE" ]; then
    log_warn "Could not fetch ETH price, using estimate: $3000"
    ETH_PRICE="3000"
fi

if [ "$LINK_PRICE" = "0" ] || [ -z "$LINK_PRICE" ]; then
    log_warn "Could not fetch LINK price, using estimate: $15"
    LINK_PRICE="15"
fi

log_info "ETH Price: \$$ETH_PRICE USD"
log_info "LINK Price: \$$LINK_PRICE USD"
log_info ""

# Get account balances
log_header "========================================="
log_header "Account Balances ($ACCOUNT)"
log_header "========================================="
log_info ""

ETH_BAL=$(cast balance "$ACCOUNT" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
ETH_BAL_ETH=$(cast --from-wei "$ETH_BAL" ether 2>/dev/null || echo "0")
ETH_BAL_USD=$(echo "scale=2; $ETH_BAL_ETH * $ETH_PRICE" | bc 2>/dev/null || echo "0")
log_success "ETH: $ETH_BAL_ETH ETH (\$$ETH_BAL_USD USD)"

LINK_CODE=$(cast code "$LINK_TOKEN" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
LINK_BAL_ETH="0"
LINK_BAL_USD="0"
if [ -n "$LINK_CODE" ] && [ "$LINK_CODE" != "0x" ]; then
    LINK_BAL=$(cast call "$LINK_TOKEN" "balanceOf(address)" "$ACCOUNT" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
    LINK_BAL_ETH=$(cast --from-wei "$LINK_BAL" ether 2>/dev/null || echo "0")
    LINK_BAL_USD=$(echo "scale=2; $LINK_BAL_ETH * $LINK_PRICE" | bc 2>/dev/null || echo "0")
    log_success "LINK: $LINK_BAL_ETH LINK (\$$LINK_BAL_USD USD)"
else
    log_warn "LINK: Token contract not deployed"
fi

WETH9_BAL=$(cast call "$WETH9" "balanceOf(address)" "$ACCOUNT" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
WETH9_BAL_ETH=$(cast --from-wei "$WETH9_BAL" ether 2>/dev/null || echo "0")
WETH9_BAL_USD=$(echo "scale=2; $WETH9_BAL_ETH * $ETH_PRICE" | bc 2>/dev/null || echo "0")
log_success "WETH9: $WETH9_BAL_ETH WETH9 (\$$WETH9_BAL_USD USD)"

WETH10_BAL=$(cast call "$WETH10" "balanceOf(address)" "$ACCOUNT" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
WETH10_BAL_ETH=$(cast --from-wei "$WETH10_BAL" ether 2>/dev/null || echo "0")
WETH10_BAL_USD=$(echo "scale=2; $WETH10_BAL_ETH * $ETH_PRICE" | bc 2>/dev/null || echo "0")
log_success "WETH10: $WETH10_BAL_ETH WETH10 (\$$WETH10_BAL_USD USD)"

TOTAL_ACCOUNT_USD=$(echo "scale=2; $ETH_BAL_USD + ${LINK_BAL_USD:-0} + $WETH9_BAL_USD + $WETH10_BAL_USD" | bc 2>/dev/null || echo "0")
log_info ""
log_info "Total Account Value: \$$TOTAL_ACCOUNT_USD USD"
log_info ""

# Get bridge contract balances
log_header "========================================="
log_header "Bridge Contract Balances"
log_header "========================================="
log_info ""

# WETH9 Bridge
ETH_BRIDGE9=$(cast balance "$WETH9_BRIDGE" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
ETH_BRIDGE9_ETH=$(cast --from-wei "$ETH_BRIDGE9" ether 2>/dev/null || echo "0")
log_info "WETH9 Bridge ($WETH9_BRIDGE):"
log_info "  ETH: $ETH_BRIDGE9_ETH ETH"

if [ -n "$LINK_CODE" ] && [ "$LINK_CODE" != "0x" ]; then
    LINK_BRIDGE9=$(cast call "$LINK_TOKEN" "balanceOf(address)" "$WETH9_BRIDGE" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
    LINK_BRIDGE9_ETH=$(cast --from-wei "$LINK_BRIDGE9" ether 2>/dev/null || echo "0")
    LINK_BRIDGE9_USD=$(echo "scale=2; $LINK_BRIDGE9_ETH * $LINK_PRICE" | bc 2>/dev/null || echo "0")
    log_info "  LINK: $LINK_BRIDGE9_ETH LINK (\$$LINK_BRIDGE9_USD USD)"
else
    log_warn "  LINK: Cannot check (token not deployed)"
    LINK_BRIDGE9_ETH="0"
fi

# WETH10 Bridge
ETH_BRIDGE10=$(cast balance "$WETH10_BRIDGE" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
ETH_BRIDGE10_ETH=$(cast --from-wei "$ETH_BRIDGE10" ether 2>/dev/null || echo "0")
log_info ""
log_info "WETH10 Bridge ($WETH10_BRIDGE):"
log_info "  ETH: $ETH_BRIDGE10_ETH ETH"

if [ -n "$LINK_CODE" ] && [ "$LINK_CODE" != "0x" ]; then
    LINK_BRIDGE10=$(cast call "$LINK_TOKEN" "balanceOf(address)" "$WETH10_BRIDGE" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
    LINK_BRIDGE10_ETH=$(cast --from-wei "$LINK_BRIDGE10" ether 2>/dev/null || echo "0")
    LINK_BRIDGE10_USD=$(echo "scale=2; $LINK_BRIDGE10_ETH * $LINK_PRICE" | bc 2>/dev/null || echo "0")
    log_info "  LINK: $LINK_BRIDGE10_ETH LINK (\$$LINK_BRIDGE10_USD USD)"
else
    log_warn "  LINK: Cannot check (token not deployed)"
    LINK_BRIDGE10_ETH="0"
fi

log_info ""

# Calculate funding requirements
log_header "========================================="
log_header "Funding Requirements"
log_header "========================================="
log_info ""

# Recommended amounts
RECOMMENDED_ETH_GAS="0.1"  # For gas fees
RECOMMENDED_LINK_PER_BRIDGE="10"  # 10 LINK per bridge (buffer for fees)
RECOMMENDED_LINK_TOTAL="20"  # 10 LINK per bridge * 2 bridges

# Calculate required amounts
REQUIRED_ETH_GAS=$(echo "scale=6; $RECOMMENDED_ETH_GAS" | bc 2>/dev/null || echo "0.1")
REQUIRED_LINK_WETH9=$(echo "scale=6; $RECOMMENDED_LINK_PER_BRIDGE - $LINK_BRIDGE9_ETH" | bc 2>/dev/null || echo "$RECOMMENDED_LINK_PER_BRIDGE")
REQUIRED_LINK_WETH10=$(echo "scale=6; $RECOMMENDED_LINK_PER_BRIDGE - $LINK_BRIDGE10_ETH" | bc 2>/dev/null || echo "$RECOMMENDED_LINK_PER_BRIDGE")

# Ensure non-negative
if (( $(echo "$REQUIRED_LINK_WETH9 < 0" | bc -l 2>/dev/null || echo 1) )); then
    REQUIRED_LINK_WETH9="0"
fi
if (( $(echo "$REQUIRED_LINK_WETH10 < 0" | bc -l 2>/dev/null || echo 1) )); then
    REQUIRED_LINK_WETH10="0"
fi

REQUIRED_LINK_TOTAL=$(echo "scale=6; $REQUIRED_LINK_WETH9 + $REQUIRED_LINK_WETH10" | bc 2>/dev/null || echo "0")

# Calculate USD values
REQUIRED_ETH_GAS_USD=$(echo "scale=2; $REQUIRED_ETH_GAS * $ETH_PRICE" | bc 2>/dev/null || echo "0")
REQUIRED_LINK_TOTAL_USD=$(echo "scale=2; $REQUIRED_LINK_TOTAL * $LINK_PRICE" | bc 2>/dev/null || echo "0")
TOTAL_REQUIRED_USD=$(echo "scale=2; $REQUIRED_ETH_GAS_USD + $REQUIRED_LINK_TOTAL_USD" | bc 2>/dev/null || echo "0")

log_info "Recommended Funding:"
log_info ""

log_info "1. Account ETH (for gas fees):"
log_info "   Current: $ETH_BAL_ETH ETH"
log_info "   Recommended: $RECOMMENDED_ETH_GAS ETH"
if (( $(echo "$ETH_BAL_ETH >= $RECOMMENDED_ETH_GAS" | bc -l 2>/dev/null || echo 1) )); then
    log_success "   Status: ✓ Sufficient"
else
    REQUIRED_ETH_ACCOUNT=$(echo "scale=6; $RECOMMENDED_ETH_GAS - $ETH_BAL_ETH" | bc 2>/dev/null || echo "0")
    REQUIRED_ETH_ACCOUNT_USD=$(echo "scale=2; $REQUIRED_ETH_ACCOUNT * $ETH_PRICE" | bc 2>/dev/null || echo "0")
    log_warn "   Status: ⚠ Need $REQUIRED_ETH_ACCOUNT ETH (\$$REQUIRED_ETH_ACCOUNT_USD USD)"
fi

log_info ""
log_info "2. WETH9 Bridge LINK:"
log_info "   Address: $WETH9_BRIDGE"
log_info "   Current: $LINK_BRIDGE9_ETH LINK"
log_info "   Recommended: $RECOMMENDED_LINK_PER_BRIDGE LINK"
if (( $(echo "$LINK_BRIDGE9_ETH >= $RECOMMENDED_LINK_PER_BRIDGE" | bc -l 2>/dev/null || echo 1) )); then
    log_success "   Status: ✓ Sufficient"
else
    REQUIRED_LINK_WETH9_USD=$(echo "scale=2; $REQUIRED_LINK_WETH9 * $LINK_PRICE" | bc 2>/dev/null || echo "0")
    log_warn "   Status: ⚠ Need $REQUIRED_LINK_WETH9 LINK (\$$REQUIRED_LINK_WETH9_USD USD)"
fi

log_info ""
log_info "3. WETH10 Bridge LINK:"
log_info "   Address: $WETH10_BRIDGE"
log_info "   Current: $LINK_BRIDGE10_ETH LINK"
log_info "   Recommended: $RECOMMENDED_LINK_PER_BRIDGE LINK"
if (( $(echo "$LINK_BRIDGE10_ETH >= $RECOMMENDED_LINK_PER_BRIDGE" | bc -l 2>/dev/null || echo 1) )); then
    log_success "   Status: ✓ Sufficient"
else
    REQUIRED_LINK_WETH10_USD=$(echo "scale=2; $REQUIRED_LINK_WETH10 * $LINK_PRICE" | bc 2>/dev/null || echo "0")
    log_warn "   Status: ⚠ Need $REQUIRED_LINK_WETH10 LINK (\$$REQUIRED_LINK_WETH10_USD USD)"
fi

log_info ""
log_header "========================================="
log_header "Summary"
log_header "========================================="
log_info ""

log_info "Current Prices:"
log_info "  ETH: \$$ETH_PRICE USD"
log_info "  LINK: \$$LINK_PRICE USD"
log_info ""

log_info "Account Balances:"
log_info "  ETH: $ETH_BAL_ETH ETH (\$$ETH_BAL_USD USD)"
if [ -n "$LINK_CODE" ] && [ "$LINK_CODE" != "0x" ]; then
    log_info "  LINK: $LINK_BAL_ETH LINK (\$$LINK_BAL_USD USD)"
fi
log_info "  WETH9: $WETH9_BAL_ETH WETH9 (\$$WETH9_BAL_USD USD)"
log_info "  WETH10: $WETH10_BAL_ETH WETH10 (\$$WETH10_BAL_USD USD)"
log_info "  Total: \$$TOTAL_ACCOUNT_USD USD"
log_info ""

log_info "Bridge Contract Balances:"
log_info "  WETH9 Bridge LINK: $LINK_BRIDGE9_ETH LINK"
log_info "  WETH10 Bridge LINK: $LINK_BRIDGE10_ETH LINK"
log_info ""

if (( $(echo "$REQUIRED_LINK_TOTAL > 0" | bc -l 2>/dev/null || echo 0) )); then
    log_warn "Funding Required:"
    log_warn "  Total LINK Needed: $REQUIRED_LINK_TOTAL LINK (\$$REQUIRED_LINK_TOTAL_USD USD)"
    log_warn "    - WETH9 Bridge: $REQUIRED_LINK_WETH9 LINK"
    log_warn "    - WETH10 Bridge: $REQUIRED_LINK_WETH10 LINK"
    log_info ""
    log_info "Transfer Commands:"
    if (( $(echo "$REQUIRED_LINK_WETH9 > 0" | bc -l 2>/dev/null || echo 0) )); then
        log_info "  Transfer $REQUIRED_LINK_WETH9 LINK to WETH9 Bridge:"
        log_info "    cast send $LINK_TOKEN 'transfer(address,uint256)' $WETH9_BRIDGE $(cast --to-wei $REQUIRED_LINK_WETH9 ether) --rpc-url $RPC_URL --private-key \$PRIVATE_KEY"
    fi
    if (( $(echo "$REQUIRED_LINK_WETH10 > 0" | bc -l 2>/dev/null || echo 0) )); then
        log_info "  Transfer $REQUIRED_LINK_WETH10 LINK to WETH10 Bridge:"
        log_info "    cast send $LINK_TOKEN 'transfer(address,uint256)' $WETH10_BRIDGE $(cast --to-wei $REQUIRED_LINK_WETH10 ether) --rpc-url $RPC_URL --private-key \$PRIVATE_KEY"
    fi
else
    log_success "✓ All bridge contracts have sufficient LINK"
fi

log_info ""
log_info "Total Funding Required: \$$TOTAL_REQUIRED_USD USD"
log_info ""
