#!/bin/bash

# Check Oracle Publisher Service Status
# Usage: ./check-oracle-publisher-status.sh

set -e

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

# Configuration (VMID 3500 on r630-02 since 2026-03-28)
PROXMOX_HOST="${PROXMOX_ORACLE_PUBLISHER_HOST:-192.168.11.12}"
VMID=3500
ORACLE_ADDRESS="0x3304b747e565a97ec8ac220b0b6a1f6ffdb837e6"
RPC_URL="${RPC_URL:-${RPC_URL_138:-http://192.168.11.211:8545}}"

echo -e "${BLUE}╔══════════════════════════════════════════════════════════════╗${NC}"
echo -e "${BLUE}║     Oracle Publisher Service Status Check                  ║${NC}"
echo -e "${BLUE}╚══════════════════════════════════════════════════════════════╝${NC}"
echo ""

# Check if container exists
echo -e "${YELLOW}1. Checking if container (VMID $VMID) exists...${NC}"
if ssh "root@$PROXMOX_HOST" "pct list | grep -q '^[[:space:]]*$VMID'" 2>/dev/null; then
    CONTAINER_STATUS=$(ssh "root@$PROXMOX_HOST" "pct status $VMID 2>/dev/null | awk '{print \$2}'" || echo "unknown")
    echo -e "${GREEN}✓ Container exists (Status: $CONTAINER_STATUS)${NC}"
else
    echo -e "${RED}✗ Container VMID $VMID not found${NC}"
    echo ""
    echo "Container needs to be created. See documentation:"
    echo "  docs/04-configuration/metamask/ORACLE_PRICE_FEED_SETUP.md"
    exit 1
fi
echo ""

# Check service status
echo -e "${YELLOW}2. Checking oracle-publisher service status...${NC}"
SERVICE_STATUS=$(ssh "root@$PROXMOX_HOST" "pct exec $VMID -- systemctl is-active oracle-publisher.service 2>/dev/null || echo 'inactive'" 2>&1)
if [ "$SERVICE_STATUS" = "active" ]; then
    echo -e "${GREEN}✓ Service is active${NC}"
    
    # Check if service is enabled
    ENABLED=$(ssh "root@$PROXMOX_HOST" "pct exec $VMID -- systemctl is-enabled oracle-publisher.service 2>/dev/null || echo 'disabled'" 2>&1)
    if [ "$ENABLED" = "enabled" ]; then
        echo -e "${GREEN}✓ Service is enabled (will start on boot)${NC}"
    else
        echo -e "${YELLOW}⚠ Service is not enabled (won't start on boot)${NC}"
    fi
else
    echo -e "${RED}✗ Service is $SERVICE_STATUS${NC}"
    echo ""
    echo "To start the service:"
    echo "  ssh root@$PROXMOX_HOST \"pct exec $VMID -- systemctl start oracle-publisher\""
    echo "  ssh root@$PROXMOX_HOST \"pct exec $VMID -- systemctl enable oracle-publisher\""
fi
echo ""

# Check configuration file
echo -e "${YELLOW}3. Checking configuration file...${NC}"
if ssh "root@$PROXMOX_HOST" "pct exec $VMID -- test -f /opt/oracle-publisher/.env" 2>/dev/null; then
    echo -e "${GREEN}✓ Configuration file exists${NC}"
    
    # Check key configuration variables
    echo "  Checking key variables..."
    ENV_VARS=("ORACLE_ADDRESS" "AGGREGATOR_ADDRESS" "RPC_URL" "CHAIN_ID" "PRIVATE_KEY" "UPDATE_INTERVAL")
    for VAR in "${ENV_VARS[@]}"; do
        VALUE=$(ssh "root@$PROXMOX_HOST" "pct exec $VMID -- grep '^${VAR}=' /opt/oracle-publisher/.env 2>/dev/null | cut -d= -f2-" || echo "")
        if [ -n "$VALUE" ]; then
            if [ "$VAR" = "PRIVATE_KEY" ]; then
                echo -e "  ${GREEN}✓${NC} $VAR = [HIDDEN]"
            else
                echo -e "  ${GREEN}✓${NC} $VAR = $VALUE"
            fi
        else
            echo -e "  ${RED}✗${NC} $VAR not set"
        fi
    done
else
    echo -e "${RED}✗ Configuration file not found at /opt/oracle-publisher/.env${NC}"
fi
echo ""

# Check recent logs
echo -e "${YELLOW}4. Checking recent service logs (last 10 lines)...${NC}"
RECENT_LOGS=$(ssh "root@$PROXMOX_HOST" "pct exec $VMID -- journalctl -u oracle-publisher.service -n 10 --no-pager 2>/dev/null" || echo "")
if [ -n "$RECENT_LOGS" ]; then
    echo "$RECENT_LOGS" | while IFS= read -r line; do
        if echo "$line" | grep -qiE "(error|failed|exception)"; then
            echo -e "  ${RED}$line${NC}"
        elif echo "$line" | grep -qiE "(price|update|success)"; then
            echo -e "  ${GREEN}$line${NC}"
        else
            echo "  $line"
        fi
    done
else
    echo -e "${YELLOW}⚠ No recent logs found${NC}"
fi
echo ""

# Check oracle contract price
echo -e "${YELLOW}5. Checking oracle contract price data...${NC}"
ORACLE_DATA=$(cast call "$ORACLE_ADDRESS" "latestRoundData()" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
if [ -n "$ORACLE_DATA" ]; then
    # Parse the response (format: roundId, answer, startedAt, updatedAt, answeredInRound)
    # Extract answer (second field, bytes 131-194)
    ANSWER_HEX=$(echo "$ORACLE_DATA" | cut -c 131-194)
    
    if [ "$ANSWER_HEX" != "00000000000000000000000000000000000000000000000000000000" ]; then
        # Convert hex to decimal
        ANSWER_DEC=$(printf "%d" "0x$ANSWER_HEX" 2>/dev/null || echo "0")
        
        # Handle signed integer (if > 2^255, it's negative)
        if [ "$ANSWER_DEC" -gt 9223372036854775807 ] 2>/dev/null; then
            ANSWER_DEC=$((ANSWER_DEC - 18446744073709551616))
        fi
        
        # Convert from 8 decimals to USD
        PRICE=$(echo "scale=2; $ANSWER_DEC / 100000000" | bc 2>/dev/null || echo "0")
        
        if [ "$PRICE" != "0" ] && [ "$PRICE" != "0.00" ]; then
            echo -e "${GREEN}✓ Oracle has price data${NC}"
            echo "  ETH/USD Price: \$$PRICE"
            
            # Extract updatedAt (fourth field)
            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
                    echo -e "${GREEN}✓ Price updated $AGE seconds ago (fresh)${NC}"
                elif [ $AGE -lt 3600 ]; then
                    MINUTES=$((AGE / 60))
                    echo -e "${YELLOW}⚠ Price updated $MINUTES minutes ago (may be stale)${NC}"
                else
                    HOURS=$((AGE / 3600))
                    echo -e "${RED}✗ Price updated $HOURS hours ago (stale)${NC}"
                fi
            fi
        else
            echo -e "${RED}✗ Oracle price is zero (needs update)${NC}"
        fi
    else
        echo -e "${RED}✗ Oracle price is zero (needs update)${NC}"
    fi
else
    echo -e "${RED}✗ Failed to query oracle contract${NC}"
fi
echo ""

# Summary
echo -e "${BLUE}╔══════════════════════════════════════════════════════════════╗${NC}"
echo -e "${BLUE}║     Summary                                                 ║${NC}"
echo -e "${BLUE}╚══════════════════════════════════════════════════════════════╝${NC}"
echo ""
echo "To view full logs:"
echo "  ssh root@$PROXMOX_HOST \"pct exec $VMID -- journalctl -u oracle-publisher.service -f\""
echo ""
echo "To restart service:"
echo "  ssh root@$PROXMOX_HOST \"pct exec $VMID -- systemctl restart oracle-publisher\""
echo ""
echo "To update oracle manually:"
echo "  cd /home/intlc/projects/proxmox/smom-dbis-138"
echo "  ./scripts/update-oracle-price.sh"
