#!/bin/bash

# Complete MetaMask Integration Check
# Verifies decimals, balances, pricing, and volumes for MetaMask
# Usage: ./check-metamask-integration.sh

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=138
RPC_URL="${RPC_URL:-${RPC_URL_138:-http://192.168.11.211:8545}}"
ORACLE_ADDRESS="0x3304b747e565a97ec8ac220b0b6a1f6ffdb837e6"

# Token addresses
WETH9="0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"
WETH10="0xf4BB2e28688e89fCcE3c0580D37d36A7672E8A9f"
CUSDT="0x93E66202A11B1772E55407B32B44e5Cd8eda7f22"
CUSDC="0xf22258f57794CC8E06237084b353Ab30fFfa640b"

# 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}║     MetaMask Integration - Complete Verification            ║${NC}"
echo -e "${BLUE}╚══════════════════════════════════════════════════════════════╝${NC}"
echo ""
echo -e "${BLUE}Chain ID:${NC} $CHAIN_ID"
echo -e "${BLUE}RPC URL:${NC} $RPC_URL"
echo ""

# ============================================================================
# 1. TOKEN DECIMALS VERIFICATION
# ============================================================================
log_section "1. Token Decimals Verification"

declare -A TOKENS=(
    ["WETH9"]="$WETH9:18"
    ["WETH10"]="$WETH10:18"
    ["cUSDT"]="$CUSDT:6"
    ["cUSDC"]="$CUSDC:6"
)

TOKEN_LIST_FILE="token-lists/lists/dbis-138.tokenlist.json"
METAMASK_LIST_FILE="docs/04-configuration/metamask/METAMASK_TOKEN_LIST.json"

for TOKEN_NAME in "${!TOKENS[@]}"; do
    IFS=':' read -r ADDRESS EXPECTED_DEC <<< "${TOKENS[$TOKEN_NAME]}"
    
    log_info "Checking $TOKEN_NAME ($ADDRESS)..."
    
    # Check on-chain decimals
    ONCHAIN_DEC=$(timeout 15 cast call "$ADDRESS" "decimals()(uint8)" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
    if [ -n "$ONCHAIN_DEC" ]; then
        DEC_DEC=$(printf "%d" "$ONCHAIN_DEC" 2>/dev/null || echo "0")
        if [ "$DEC_DEC" = "$EXPECTED_DEC" ]; then
            log_success "$TOKEN_NAME: On-chain decimals correct ($DEC_DEC)"
        else
            log_warn "$TOKEN_NAME: On-chain decimals mismatch (got $DEC_DEC, expected $EXPECTED_DEC)"
        fi
    else
        log_error "$TOKEN_NAME: Failed to fetch on-chain decimals"
    fi
    
    # Check token list decimals
    if [ -f "$TOKEN_LIST_FILE" ]; then
        LIST_DEC=$(grep -A 10 "\"$ADDRESS\"" "$TOKEN_LIST_FILE" 2>/dev/null | grep "decimals" | head -1 | grep -oE "[0-9]+" || echo "")
        if [ -n "$LIST_DEC" ] && [ "$LIST_DEC" = "$EXPECTED_DEC" ]; then
            log_success "$TOKEN_NAME: Token list decimals correct ($LIST_DEC)"
        elif [ -n "$LIST_DEC" ]; then
            log_warn "$TOKEN_NAME: Token list decimals mismatch (got $LIST_DEC, expected $EXPECTED_DEC)"
        else
            log_warn "$TOKEN_NAME: Not found in token list"
        fi
    fi
    
    # Check MetaMask token list
    if [ -f "$METAMASK_LIST_FILE" ]; then
        META_DEC=$(grep -A 10 "\"$ADDRESS\"" "$METAMASK_LIST_FILE" 2>/dev/null | grep "decimals" | head -1 | grep -oE "[0-9]+" || echo "")
        if [ -n "$META_DEC" ] && [ "$META_DEC" = "$EXPECTED_DEC" ]; then
            log_success "$TOKEN_NAME: MetaMask list decimals correct ($META_DEC)"
        elif [ -n "$META_DEC" ]; then
            log_warn "$TOKEN_NAME: MetaMask list decimals mismatch (got $META_DEC, expected $EXPECTED_DEC)"
        fi
    fi
    echo ""
done

# ============================================================================
# 2. BALANCE DISPLAY VERIFICATION
# ============================================================================
log_section "2. Balance Display Verification"

log_info "Testing balanceOf for sample addresses..."

# Test with zero address
TEST_ADDRESS="0x0000000000000000000000000000000000000000"
for TOKEN_NAME in "${!TOKENS[@]}"; do
    IFS=':' read -r ADDRESS EXPECTED_DEC <<< "${TOKENS[$TOKEN_NAME]}"
    
    BALANCE=$(timeout 15 cast call "$ADDRESS" "balanceOf(address)(uint256)" "$TEST_ADDRESS" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
    if [ -n "$BALANCE" ]; then
        log_success "$TOKEN_NAME: balanceOf() function works"
    else
        log_error "$TOKEN_NAME: balanceOf() function failed"
    fi
done

# ============================================================================
# 3. ORACLE PRICE FEED VERIFICATION
# ============================================================================
log_section "3. Oracle Price Feed Verification"

log_info "Checking oracle contract..."
ORACLE_DATA=$(timeout 15 cast call "$ORACLE_ADDRESS" "latestRoundData()" --rpc-url "$RPC_URL" 2>/dev/null || echo "")

if [ -n "$ORACLE_DATA" ] && [ "$ORACLE_DATA" != "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" ]; then
    # Extract answer (second field)
    ANSWER_HEX=$(echo "$ORACLE_DATA" | cut -c 131-194)
    ANSWER_DEC=$(printf "%d" "0x$ANSWER_HEX" 2>/dev/null || echo "0")
    
    if [ "$ANSWER_DEC" != "0" ] && [ "$ANSWER_DEC" -gt 0 ]; then
        PRICE=$(echo "scale=2; $ANSWER_DEC / 100000000" | bc 2>/dev/null || echo "0")
        log_success "Oracle has price data: ETH/USD = \$$PRICE"
        
        # Check update timestamp
        UPDATED_AT_HEX=$(echo "$ORACLE_DATA" | cut -c 259-322)
        UPDATED_AT=$(printf "%d" "0x$UPDATED_AT_HEX" 2>/dev/null || echo "0")
        if [ "$UPDATED_AT" != "0" ]; then
            CURRENT_TIME=$(date +%s)
            AGE=$((CURRENT_TIME - UPDATED_AT))
            if [ $AGE -lt 300 ]; then
                log_success "Oracle price is fresh (updated $AGE seconds ago)"
            else
                MINUTES=$((AGE / 60))
                log_warn "Oracle price may be stale (updated $MINUTES minutes ago)"
            fi
        fi
    else
        log_error "Oracle price is zero (needs update)"
    fi
else
    log_error "Oracle contract returns zero or empty data"
fi

log_info ""
log_warn "IMPORTANT: MetaMask does NOT automatically query oracle contracts"
log_info "MetaMask uses CoinGecko API for USD prices (requires token listing)"

# ============================================================================
# 4. METAMASK PRICE SOURCE VERIFICATION
# ============================================================================
log_section "4. MetaMask Price Source Verification"

log_info "MetaMask Price Sources (in order):"
echo "  1. CoinGecko API (primary) - requires token listing"
echo "  2. Token Lists - limited price metadata support"
echo "  3. Oracle Contracts - NOT automatically queried"
echo ""

log_info "Checking CoinGecko listing status..."

# Check if tokens are likely on CoinGecko
TOKENS_TO_CHECK=("ethereum" "tether" "usd-coin")
for TOKEN_ID in "${TOKENS_TO_CHECK[@]}"; do
    COINGECKO_DATA=$(curl -s "https://api.coingecko.com/api/v3/simple/price?ids=$TOKEN_ID&vs_currencies=usd" --max-time 5 2>/dev/null || echo "")
    if echo "$COINGECKO_DATA" | grep -q "usd"; then
        log_success "CoinGecko API accessible for $TOKEN_ID"
    else
        log_warn "CoinGecko API may not have data for $TOKEN_ID"
    fi
done

log_info ""
log_warn "Note: cUSDT and cUSDC are NOT listed on CoinGecko yet"
log_info "See: docs/04-configuration/coingecko/COINGECKO_SUBMISSION_GUIDE.md"

# ============================================================================
# 5. VOLUME DATA VERIFICATION
# ============================================================================
log_section "5. Volume Data Verification"

log_info "MetaMask Volume Data Sources:"
echo "  - CoinGecko API (if token is listed)"
echo "  - Token Lists (limited support)"
echo "  - Oracle contracts (NOT used by MetaMask)"
echo ""

log_warn "MetaMask does NOT display volume data from oracles"
log_info "Volume data comes from CoinGecko or external APIs"

# Check if token aggregation service exists
TOKEN_AGG_SERVICE="smom-dbis-138/services/token-aggregation"
if [ -d "$TOKEN_AGG_SERVICE" ]; then
    log_success "Token aggregation service exists"
    log_info "  Service can aggregate volume data from multiple sources"
    log_info "  But MetaMask doesn't query this service directly"
else
    log_warn "Token aggregation service not found"
fi

# ============================================================================
# 6. TOKEN LIST HOSTING VERIFICATION
# ============================================================================
log_section "6. Token List Hosting Verification"

TOKEN_LIST_URL="https://raw.githubusercontent.com/Defi-Oracle-Meta-Blockchain/metamask-integration/main/config/token-list.json"
log_info "Checking hosted token list..."
if curl -s -I "$TOKEN_LIST_URL" --max-time 5 | head -1 | grep -q "200\|301\|302"; then
    log_success "Token list is hosted and accessible"
    log_info "  URL: $TOKEN_LIST_URL"
    
    # Check if list has correct decimals
    LIST_CONTENT=$(curl -s "$TOKEN_LIST_URL" --max-time 5 2>/dev/null || echo "")
    if echo "$LIST_CONTENT" | grep -q "\"decimals\": 18"; then
        log_success "Token list includes 18 decimals entries"
    fi
    if echo "$LIST_CONTENT" | grep -q "\"decimals\": 6"; then
        log_success "Token list includes 6 decimals entries"
    fi
else
    log_warn "Token list may not be accessible at hosted URL"
fi

# ============================================================================
# SUMMARY
# ============================================================================
log_section "Verification 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 ""

echo -e "${CYAN}Key Findings:${NC}"
echo ""
echo "1. ${GREEN}Decimals:${NC} Token lists override on-chain decimals"
echo "   - WETH9: Contract returns 0, but token list has 18 ✅"
echo "   - cUSDT/cUSDC: Both contract and list have 6 ✅"
echo ""
echo "2. ${YELLOW}Pricing:${NC} MetaMask uses CoinGecko, NOT oracles"
echo "   - Oracle exists but MetaMask doesn't query it"
echo "   - cUSDT/cUSDC need CoinGecko listing for USD display"
echo ""
echo "3. ${YELLOW}Volumes:${NC} MetaMask doesn't display volume from oracles"
echo "   - Volume data comes from CoinGecko/external APIs"
echo "   - Oracle contracts don't provide volume data"
echo ""
echo "4. ${GREEN}Balances:${NC} ERC-20 functions work correctly"
echo "   - balanceOf() works for all tokens"
echo "   - Display depends on correct decimals in token list"
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 "${YELLOW}╔══════════════════════════════════════════════════════════════╗${NC}"
    echo -e "${YELLOW}║     Some Checks Need Attention                              ║${NC}"
    echo -e "${YELLOW}╚══════════════════════════════════════════════════════════════╝${NC}"
    exit 1
fi
