#!/bin/bash

# Complete Checklist for AUSDT on ALL MAINNET (ChainID 651940)
# Usage: ./check-ausdt-all-mainnet.sh

# Don't exit on error - we want to continue checking
set +e

# Colors
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
NC='\033[0m'

# Configuration
CHAIN_ID=651940
AUSDT_ADDRESS="0x015B1897Ed5279930bC2Be46F661894d219292A6"
RPC_URL="${RPC_URL_651940:-https://mainnet-rpc.alltra.global}"
EXPLORER_URL="https://alltra.global"

# Counters
PASSED=0
FAILED=0
WARNINGS=0

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[✓]${NC} $1"; ((PASSED++)); }
log_error() { echo -e "${RED}[✗]${NC} $1"; ((FAILED++)); }
log_warn() { echo -e "${YELLOW}[⚠]${NC} $1"; ((WARNINGS++)); }
log_section() { echo -e "\n${CYAN}══════════════════════════════════════════════════════════════${NC}"; echo -e "${CYAN}$1${NC}"; echo -e "${CYAN}══════════════════════════════════════════════════════════════${NC}\n"; }

echo -e "${BLUE}╔══════════════════════════════════════════════════════════════╗${NC}"
echo -e "${BLUE}║     AUSDT on ALL MAINNET - Complete Checklist              ║${NC}"
echo -e "${BLUE}╚══════════════════════════════════════════════════════════════╝${NC}"
echo ""
echo -e "${BLUE}Token Address:${NC} $AUSDT_ADDRESS"
echo -e "${BLUE}Chain ID:${NC} $CHAIN_ID (ALL Mainnet)"
echo -e "${BLUE}RPC URL:${NC} $RPC_URL"
echo -e "${BLUE}Explorer:${NC} $EXPLORER_URL"
echo ""

# ============================================================================
# 1. RPC CONNECTIVITY
# ============================================================================
log_section "1. RPC Connectivity Check"

log_info "Testing RPC endpoint connectivity..."
if curl -s -X POST -H "Content-Type: application/json" \
    --data '{"jsonrpc":"2.0","method":"eth_chainId","params":[],"id":1}' \
    --max-time 10 "$RPC_URL" > /dev/null 2>&1; then
    log_success "RPC endpoint is accessible"
    
    # Verify chain ID (with timeout)
    CHAIN_ID_RESPONSE=$(timeout 10 curl -s -X POST -H "Content-Type: application/json" \
        --data '{"jsonrpc":"2.0","method":"eth_chainId","params":[],"id":1}' \
        --max-time 10 "$RPC_URL" 2>/dev/null | python3 -c "import sys, json; print(json.load(sys.stdin).get('result', ''))" 2>/dev/null || echo "")
    
    if [ -n "$CHAIN_ID_RESPONSE" ] && [ "$CHAIN_ID_RESPONSE" != "" ]; then
        CHAIN_ID_DEC=$(printf "%d" "$CHAIN_ID_RESPONSE" 2>/dev/null || echo "0")
        if [ "$CHAIN_ID_DEC" = "$CHAIN_ID" ]; then
            log_success "Chain ID matches: $CHAIN_ID"
        else
            log_warn "Chain ID mismatch: Expected $CHAIN_ID, got $CHAIN_ID_DEC (may be hex format)"
        fi
    else
        log_warn "Could not verify chain ID (RPC may be slow)"
    fi
else
    log_error "RPC endpoint is not accessible"
fi

# ============================================================================
# 2. CONTRACT DEPLOYMENT
# ============================================================================
log_section "2. Contract Deployment Verification"

log_info "Checking if contract is deployed..."
CONTRACT_CODE=$(timeout 15 cast code "$AUSDT_ADDRESS" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
if [ -n "$CONTRACT_CODE" ] && [ "$CONTRACT_CODE" != "0x" ] && [ "$CONTRACT_CODE" != "" ]; then
    CODE_SIZE=$(echo "$CONTRACT_CODE" | wc -c)
    if [ "$CODE_SIZE" -gt 10 ]; then
        log_success "Contract is deployed (code size: $CODE_SIZE bytes)"
    else
        log_error "Contract code is empty or invalid"
    fi
else
    log_error "Contract is not deployed or not accessible"
fi

# ============================================================================
# 3. TOKEN METADATA
# ============================================================================
log_section "3. Token Metadata Verification"

log_info "Fetching token name..."
TOKEN_NAME=$(timeout 15 cast call "$AUSDT_ADDRESS" "name()(string)" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
if [ -n "$TOKEN_NAME" ] && [ "$TOKEN_NAME" != "" ]; then
    log_success "Token Name: $TOKEN_NAME"
else
    log_error "Failed to fetch token name"
fi

log_info "Fetching token symbol..."
TOKEN_SYMBOL=$(timeout 15 cast call "$AUSDT_ADDRESS" "symbol()(string)" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
if [ -n "$TOKEN_SYMBOL" ] && [ "$TOKEN_SYMBOL" != "" ]; then
    # Remove quotes if present
    TOKEN_SYMBOL_CLEAN=$(echo "$TOKEN_SYMBOL" | tr -d '"')
    log_success "Token Symbol: $TOKEN_SYMBOL_CLEAN"
    if [ "$TOKEN_SYMBOL_CLEAN" = "AUSDT" ]; then
        log_success "Symbol matches expected: AUSDT"
    else
        log_warn "Symbol mismatch: Expected AUSDT, got $TOKEN_SYMBOL_CLEAN"
    fi
else
    log_error "Failed to fetch token symbol"
fi

log_info "Fetching token decimals..."
TOKEN_DECIMALS=$(timeout 15 cast call "$AUSDT_ADDRESS" "decimals()(uint8)" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
if [ -n "$TOKEN_DECIMALS" ]; then
    DECIMALS_DEC=$(printf "%d" "$TOKEN_DECIMALS" 2>/dev/null || echo "0")
    log_success "Token Decimals: $DECIMALS_DEC"
    if [ "$DECIMALS_DEC" = "18" ]; then
        log_success "Decimals match expected: 18"
    else
        log_warn "Decimals mismatch: Expected 18, got $DECIMALS_DEC"
    fi
else
    log_error "Failed to fetch token decimals"
fi

# ============================================================================
# 4. TOKEN SUPPLY
# ============================================================================
log_section "4. Token Supply Information"

log_info "Fetching total supply..."
TOTAL_SUPPLY=$(timeout 15 cast call "$AUSDT_ADDRESS" "totalSupply()(uint256)" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
if [ -n "$TOTAL_SUPPLY" ] && [ "$TOTAL_SUPPLY" != "0x0" ] && [ "$TOTAL_SUPPLY" != "0" ]; then
    SUPPLY_DEC=$(printf "%d" "$TOTAL_SUPPLY" 2>/dev/null || echo "0")
    if [ "$DECIMALS_DEC" = "18" ]; then
        SUPPLY_DISPLAY=$(echo "scale=2; $SUPPLY_DEC / 1000000000000000000" | bc 2>/dev/null || echo "$SUPPLY_DEC")
        log_success "Total Supply: $SUPPLY_DISPLAY AUSDT"
    else
        log_success "Total Supply: $SUPPLY_DEC (raw)"
    fi
else
    log_warn "Total supply is zero or could not be fetched"
fi

# ============================================================================
# 5. ERC-20 FUNCTIONALITY
# ============================================================================
log_section "5. ERC-20 Functionality Check"

log_info "Testing balanceOf function..."
BALANCE=$(timeout 15 cast call "$AUSDT_ADDRESS" "balanceOf(address)(uint256)" "0x0000000000000000000000000000000000000000" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
if [ -n "$BALANCE" ]; then
    log_success "balanceOf() function works"
else
    log_error "balanceOf() function failed"
fi

log_info "Testing allowance function..."
ALLOWANCE=$(timeout 15 cast call "$AUSDT_ADDRESS" "allowance(address,address)(uint256)" "0x0000000000000000000000000000000000000000" "0x0000000000000000000000000000000000000000" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
if [ -n "$ALLOWANCE" ]; then
    log_success "allowance() function works"
else
    log_error "allowance() function failed"
fi

# ============================================================================
# 6. TOKEN LIST VERIFICATION
# ============================================================================
log_section "6. Token List Integration"

TOKEN_LIST_FILE="token-lists/lists/all-mainnet.tokenlist.json"
if [ -f "$TOKEN_LIST_FILE" ]; then
    log_success "Token list file exists: $TOKEN_LIST_FILE"
    
    if grep -q "$AUSDT_ADDRESS" "$TOKEN_LIST_FILE"; then
        log_success "AUSDT address found in token list"
    else
        log_error "AUSDT address not found in token list"
    fi
else
    log_error "Token list file not found: $TOKEN_LIST_FILE"
fi

# ============================================================================
# SUMMARY
# ============================================================================
log_section "Checklist Summary"

echo ""
echo -e "${CYAN}Results:${NC}"
echo -e "  ${GREEN}✓ Passed:${NC} $PASSED"
echo -e "  ${RED}✗ Failed:${NC} $FAILED"
echo -e "  ${YELLOW}⚠ Warnings:${NC} $WARNINGS"
echo ""

if [ $FAILED -eq 0 ]; then
    echo -e "${GREEN}╔══════════════════════════════════════════════════════════════╗${NC}"
    echo -e "${GREEN}║     All Critical Checks Passed!                            ║${NC}"
    echo -e "${GREEN}╚══════════════════════════════════════════════════════════════╝${NC}"
    exit 0
else
    echo -e "${RED}╔══════════════════════════════════════════════════════════════╗${NC}"
    echo -e "${RED}║     Some Checks Failed - Review Above                       ║${NC}"
    echo -e "${RED}╚══════════════════════════════════════════════════════════════╝${NC}"
    exit 1
fi
