#!/usr/bin/env bash
# Get total supply for CompliantUSDT and CompliantUSDC tokens
# Usage: ./get-usdt-usdc-supply.sh

set -euo pipefail

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'
NC='\033[0m'

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[✓]${NC} $1"; }
log_error() { echo -e "${RED}[✗]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[⚠]${NC} $1"; }

if [[ -f "$SCRIPT_DIR/lib/deployment/dotenv.sh" ]]; then
  # shellcheck disable=SC1090
  source "$SCRIPT_DIR/lib/deployment/dotenv.sh"
  load_deployment_env --repo-root "$PROJECT_ROOT"
elif [ -f "$PROJECT_ROOT/.env" ]; then
    set -a && source "$PROJECT_ROOT/.env" && set +a
fi

# Configuration
RPC_URL="${RPC_URL:-${RPC_URL_138:-http://192.168.11.211:8545}}"
RPC_URL="${RPC_URL%$'\r'}"
RPC_URL="${RPC_URL%$'\n'}"
COMPLIANT_USDT_ADDRESS="${COMPLIANT_USDT_ADDRESS:-0x93E66202A11B1772E55407B32B44e5Cd8eda7f22}"
COMPLIANT_USDC_ADDRESS="${COMPLIANT_USDC_ADDRESS:-0xf22258f57794CC8E06237084b353Ab30fFfa640b}"

# Token decimals (both USDT and USDC use 6 decimals)
USDT_DECIMALS=6
USDC_DECIMALS=6

log_info "========================================="
log_info "USDT and USDC Total Supply"
log_info "========================================="
log_info ""
log_info "RPC URL: $RPC_URL"
log_info ""

# Function to query total supply
query_total_supply() {
    local token_address=$1
    local token_name=$2
    local decimals=$3
    
    log_info "$token_name Token Information:"
    log_info "  Address: $token_address"
    
    # Get total supply
    TOTAL_SUPPLY_RAW=$(cast call "$token_address" "totalSupply()" --rpc-url "$RPC_URL" 2>&1 || echo "ERROR")
    
    if [ "$TOTAL_SUPPLY_RAW" = "ERROR" ] || [ -z "$TOTAL_SUPPLY_RAW" ]; then
        log_error "  Failed to query totalSupply()"
        log_error "  Check if contract is deployed and RPC is accessible"
        return 1
    fi
    
    # Convert hex to decimal if needed
    if echo "$TOTAL_SUPPLY_RAW" | grep -q "^0x"; then
        TOTAL_SUPPLY_DEC=$(cast --to-dec "$TOTAL_SUPPLY_RAW" 2>/dev/null || echo "0")
    else
        TOTAL_SUPPLY_DEC="$TOTAL_SUPPLY_RAW"
    fi
    
    # Convert to human-readable format (divide by 10^decimals)
    # Using bc for precision
    DIVISOR=$(echo "10^$decimals" | bc)
    TOTAL_SUPPLY_FORMATTED=$(echo "scale=$decimals; $TOTAL_SUPPLY_DEC / $DIVISOR" | bc 2>/dev/null || echo "0")
    
    log_info "  Raw Total Supply: $TOTAL_SUPPLY_DEC (wei/base units)"
    log_info "  Decimals: $decimals"
    log_success "  Total Supply: $TOTAL_SUPPLY_FORMATTED $token_name"
    
    # Also get name and symbol if possible
    TOKEN_NAME=$(cast call "$token_address" "name()" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
    TOKEN_SYMBOL=$(cast call "$token_address" "symbol()" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
    
    if [ -n "$TOKEN_NAME" ] && [ "$TOKEN_NAME" != "0x" ]; then
        TOKEN_NAME_CLEAN=$(echo "$TOKEN_NAME" | cast --to-ascii 2>/dev/null | tr -d '\0' || echo "$TOKEN_NAME")
        log_info "  Name: $TOKEN_NAME_CLEAN"
    fi
    
    if [ -n "$TOKEN_SYMBOL" ] && [ "$TOKEN_SYMBOL" != "0x" ]; then
        TOKEN_SYMBOL_CLEAN=$(echo "$TOKEN_SYMBOL" | cast --to-ascii 2>/dev/null | tr -d '\0' || echo "$TOKEN_SYMBOL")
        log_info "  Symbol: $TOKEN_SYMBOL_CLEAN"
    fi
    
    log_info ""
    
    # Return the formatted value (for potential use in other scripts)
    echo "$TOTAL_SUPPLY_FORMATTED"
}

# Query USDT
log_info "Querying CompliantUSDT..."
USDT_SUPPLY=$(query_total_supply "$COMPLIANT_USDT_ADDRESS" "USDT" "$USDT_DECIMALS")
USDT_RESULT=$?

# Query USDC
log_info "Querying CompliantUSDC..."
USDC_SUPPLY=$(query_total_supply "$COMPLIANT_USDC_ADDRESS" "USDC" "$USDC_DECIMALS")
USDC_RESULT=$?

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

if [ "$USDT_RESULT" -eq 0 ]; then
    log_success "USDT Total Supply: $USDT_SUPPLY"
else
    log_error "USDT: Failed to query"
fi

if [ "$USDC_RESULT" -eq 0 ]; then
    log_success "USDC Total Supply: $USDC_SUPPLY"
else
    log_error "USDC: Failed to query"
fi

log_info ""

