#!/usr/bin/env bash
# Test Oracle price feed functionality
# Usage: ./test-oracle-price-feed.sh

set -euo pipefail

ORACLE_PROXY="0x3304b747e565a97ec8ac220b0b6a1f6ffdb837e6"
RPC_URL="http://192.168.11.250:8545"

# 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_warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }

log_info "========================================="
log_info "Oracle Price Feed Test"
log_info "========================================="
log_info ""

# Test 1: Check RPC connectivity
log_info "Test 1: Checking RPC connectivity..."
RPC_TEST=$(curl -s -X POST "$RPC_URL" \
    -H 'Content-Type: application/json' \
    -d '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}' 2>/dev/null)

if echo "$RPC_TEST" | grep -q '"result"'; then
    BLOCK=$(echo "$RPC_TEST" | python3 -c "import sys, json; data=json.load(sys.stdin); print(int(data.get('result', '0x0'), 16))" 2>/dev/null || echo "0")
    log_success "RPC is accessible (Current Block: $BLOCK)"
else
    log_error "RPC connection failed"
    exit 1
fi

# Test 2: Check Oracle contract exists
log_info ""
log_info "Test 2: Checking Oracle contract deployment..."
ORACLE_CODE=$(curl -s -X POST "$RPC_URL" \
    -H 'Content-Type: application/json' \
    -d "{\"jsonrpc\":\"2.0\",\"method\":\"eth_getCode\",\"params\":[\"$ORACLE_PROXY\",\"latest\"],\"id\":1}" 2>/dev/null)

if echo "$ORACLE_CODE" | grep -q '"result"' && ! echo "$ORACLE_CODE" | grep -q '"0x"'; then
    CODE_LENGTH=$(echo "$ORACLE_CODE" | python3 -c "import sys, json; data=json.load(sys.stdin); print(len(data.get('result', '')))" 2>/dev/null || echo "0")
    log_success "Oracle contract is deployed (Code length: $CODE_LENGTH bytes)"
else
    log_error "Oracle contract not found at $ORACLE_PROXY"
    exit 1
fi

# Test 3: Get latest round data (latestRoundData function)
log_info ""
log_info "Test 3: Reading latest price from Oracle..."
# Function signature: latestRoundData() returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound)
# Function selector: 0x50d25bcd
LATEST_ROUND=$(curl -s -X POST "$RPC_URL" \
    -H 'Content-Type: application/json' \
    -d "{\"jsonrpc\":\"2.0\",\"method\":\"eth_call\",\"params\":[{\"to\":\"$ORACLE_PROXY\",\"data\":\"0x50d25bcd\"},\"latest\"],\"id\":1}" 2>/dev/null)

if echo "$LATEST_ROUND" | grep -q '"result"'; then
    RESULT=$(echo "$LATEST_ROUND" | python3 -c "import sys, json; data=json.load(sys.stdin); print(data.get('result', '0x0'))" 2>/dev/null)
    
    if [ "$RESULT" != "0x0" ] && [ ${#RESULT} -gt 2 ]; then
        # Parse the result (5 values returned)
        # Extract answer (second value, 32 bytes starting at position 64)
        ANSWER_HEX=$(echo "$RESULT" | cut -c 131-194)  # Position 64-128 (32 bytes = 64 hex chars)
        UPDATED_AT_HEX=$(echo "$RESULT" | cut -c 195-258)  # Position 128-192
        
        if [ -n "$ANSWER_HEX" ] && [ "$ANSWER_HEX" != "0000000000000000000000000000000000000000000000000000000000000000" ]; then
            # Convert from hex to decimal, handle negative numbers
            ANSWER_DEC=$(python3 -c "
import sys
hex_val = '0x$ANSWER_HEX'
val = int(hex_val, 16)
# Handle two's complement for negative numbers
if val > 2**255:
    val = val - 2**256
print(val)
" 2>/dev/null || echo "0")
            
            PRICE=$(python3 -c "print($ANSWER_DEC / 1e8)" 2>/dev/null || echo "0")
            UPDATED_AT=$(python3 -c "print(int('0x$UPDATED_AT_HEX', 16))" 2>/dev/null || echo "0")
            
            if [ "$PRICE" != "0" ] && [ "$UPDATED_AT" != "0" ]; then
                log_success "Oracle price feed is working!"
                log_info "  ETH/USD Price: \$$(printf '%.2f' $PRICE)"
                log_info "  Last Updated: $(date -d @$UPDATED_AT 2>/dev/null || echo 'Unknown')"
                log_info "  Timestamp: $UPDATED_AT"
            else
                log_warn "Oracle returned zero values (may need price update)"
            fi
        else
            log_warn "Oracle returned zero answer (price may not be set yet)"
        fi
    else
        log_warn "Oracle call returned empty result"
    fi
else
    log_error "Failed to call Oracle contract"
    exit 1
fi

# Test 4: Check if Oracle Publisher service is updating prices
log_info ""
log_info "Test 4: Checking Oracle Publisher service status..."
if sshpass -p 'L@kers2010' ssh -o StrictHostKeyChecking=no root@192.168.11.10 "pct list | grep -q '3500'" 2>/dev/null; then
    SERVICE_STATUS=$(sshpass -p 'L@kers2010' ssh -o StrictHostKeyChecking=no root@192.168.11.10 \
        "pct exec 3500 -- systemctl is-active oracle-publisher 2>/dev/null || echo 'inactive'" 2>&1)
    
    if [ "$SERVICE_STATUS" = "active" ]; then
        log_success "Oracle Publisher service is active"
    else
        log_warn "Oracle Publisher service is not active (status: $SERVICE_STATUS)"
        log_info "  Service may need to be started or configured"
    fi
else
    log_warn "Oracle Publisher container (VMID 3500) not found"
fi

log_info ""
log_success "========================================="
log_success "Oracle Price Feed Test Complete!"
log_success "========================================="
log_info ""
log_info "Summary:"
log_info "  - RPC connectivity: ✅"
log_info "  - Oracle contract: ✅ Deployed"
log_info "  - Price feed: $(if [ "$PRICE" != "0" ]; then echo '✅ Working'; else echo '⏳ Needs update'; fi)"
log_info ""

