#!/bin/bash
#
# Check status of all 5 local peers
#

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"

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

echo -e "${CYAN}╔═══════════════════════════════════════════════════╗${NC}"
echo -e "${CYAN}║         5-Peer Network Status Check              ║${NC}"
echo -e "${CYAN}╚═══════════════════════════════════════════════════╝${NC}"
echo ""

if [ ! -f .peers.pid ]; then
    echo -e "${RED}✗ No peers running (.peers.pid not found)${NC}"
    echo -e "${YELLOW}Run ./launch_5peers.sh to start peers${NC}"
    exit 1
fi

# Read PIDs
PIDS=($(cat .peers.pid))
PORTS=(9095 9097 9099 9101 9103)
API_PORTS=(8091 8092 8093 8094 8095)
METRICS_PORTS=(9096 9098 9100 9102 9104)

echo -e "${BLUE}Peer Status:${NC}"
echo ""

RUNNING_COUNT=0
for i in {0..4}; do
    PEER_NUM=$((i + 1))
    PID=${PIDS[$i]}
    PORT=${PORTS[$i]}
    API_PORT=${API_PORTS[$i]}
    METRICS_PORT=${METRICS_PORTS[$i]}

    if ps -p $PID > /dev/null 2>&1; then
        echo -e "${GREEN}✓ Peer $PEER_NUM${NC} │ PID: $PID │ Port: $PORT │ API: $API_PORT │ Metrics: $METRICS_PORT"
        RUNNING_COUNT=$((RUNNING_COUNT + 1))
    else
        echo -e "${RED}✗ Peer $PEER_NUM${NC} │ PID: $PID │ Port: $PORT │ ${RED}STOPPED${NC}"
    fi
done

echo ""
echo -e "${CYAN}═══════════════════════════════════════════════════${NC}"
echo -e "  ${BLUE}Running Peers:${NC}  $RUNNING_COUNT / 5"

if [ $RUNNING_COUNT -ge 3 ]; then
    echo -e "  ${BLUE}Consensus:${NC}      ${GREEN}✓ QUORUM AVAILABLE${NC} (need 3/4 validators)"
elif [ $RUNNING_COUNT -ge 1 ]; then
    echo -e "  ${BLUE}Consensus:${NC}      ${YELLOW}⚠ BELOW QUORUM${NC} (need 3/4 validators)"
else
    echo -e "  ${BLUE}Consensus:${NC}      ${RED}✗ NETWORK DOWN${NC}"
fi

echo -e "${CYAN}═══════════════════════════════════════════════════${NC}"
echo ""

# Check recent activity
if [ $RUNNING_COUNT -gt 0 ]; then
    echo -e "${BLUE}Recent Activity (last 5 lines from each peer):${NC}"
    echo ""

    for i in {0..4}; do
        PEER_NUM=$((i + 1))
        PID=${PIDS[$i]}

        if ps -p $PID > /dev/null 2>&1; then
            echo -e "${CYAN}Peer $PEER_NUM:${NC}"
            if [ -f "logs/peer${PEER_NUM}.log" ]; then
                tail -n 5 "logs/peer${PEER_NUM}.log" | sed 's/^/  /'
            else
                echo -e "  ${YELLOW}(no log file yet)${NC}"
            fi
            echo ""
        fi
    done
fi

# Consensus check
echo -e "${CYAN}═══════════════════════════════════════════════════${NC}"
echo -e "${BLUE}Consensus Check:${NC}"
echo ""

if [ $RUNNING_COUNT -ge 3 ]; then
    # Check if logs show consensus activity
    CONSENSUS_LINES=$(grep -h "checkpoint\|consensus\|PHASE" logs/peer*.log 2>/dev/null | tail -5 || true)
    if [ -n "$CONSENSUS_LINES" ]; then
        echo "$CONSENSUS_LINES" | sed 's/^/  /'
    else
        echo -e "  ${YELLOW}(waiting for consensus activity...)${NC}"
    fi
else
    echo -e "  ${RED}✗ Insufficient peers for consensus (need at least 3)${NC}"
fi

echo ""
echo -e "${CYAN}═══════════════════════════════════════════════════${NC}"
echo ""
