#!/bin/bash
#
# Launch 5 Local Peers for Analog Mainnet V4.2-Hybrid
# Framework-native containers (not Docker!)
#

set -e

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

CONFIG_FILE="config/local_5peers.json"
BINARY="./analog_codec_v42_hybrid"

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

echo -e "${CYAN}╔═══════════════════════════════════════════════════╗${NC}"
echo -e "${CYAN}║   Analog Mainnet V4.2-Hybrid: 5-Peer Testnet    ║${NC}"
echo -e "${CYAN}╚═══════════════════════════════════════════════════╝${NC}"
echo ""

# Check if binary exists
if [ ! -f "$BINARY" ]; then
    echo -e "${RED}✗ Binary not found: $BINARY${NC}"
    echo -e "${YELLOW}Building analog_codec_v42_hybrid...${NC}"
    make v42-hybrid
    echo -e "${GREEN}✓ Build complete${NC}"
    echo ""
fi

# Check if config exists
if [ ! -f "$CONFIG_FILE" ]; then
    echo -e "${RED}✗ Config not found: $CONFIG_FILE${NC}"
    exit 1
fi

# Create directories
echo -e "${BLUE}Creating peer directories...${NC}"
mkdir -p data/{peer1,peer2,peer3,peer4,peer5}
mkdir -p logs
echo -e "${GREEN}✓ Directories created${NC}"
echo ""

# Kill existing peer processes
echo -e "${YELLOW}Cleaning up existing peer processes...${NC}"
pkill -f "analog_codec_v42_hybrid.*peer" || true
sleep 1
echo -e "${GREEN}✓ Cleanup complete${NC}"
echo ""

# Launch Peer 1 (Primary/Bootstrap)
echo -e "${GREEN}▶ Launching Peer 1 (Primary)...${NC}"
echo -e "   Port: 9095 │ API: 8091 │ Metrics: 9096"
nohup $BINARY \
    --node-id 1 \
    --name "Local-Peer-1" \
    --port 9095 \
    --api-port 8091 \
    --metrics-port 9096 \
    --data-dir ./data/peer1 \
    --mode validator \
    --genesis 0x6b3a8e7f2d9c4a1b5e8f3d7c2a9b6e4f1c8d5a7b3e9f2c6a4d8b1e7f5c3a9b6e \
    > logs/peer1.log 2>&1 &
PEER1_PID=$!
echo -e "   ${CYAN}PID: $PEER1_PID${NC}"
sleep 2

# Launch Peer 2
echo -e "${GREEN}▶ Launching Peer 2...${NC}"
echo -e "   Port: 9097 │ API: 8092 │ Metrics: 9098 │ Bootstrap: localhost:9095"
nohup $BINARY \
    --node-id 2 \
    --name "Local-Peer-2" \
    --port 9097 \
    --api-port 8092 \
    --metrics-port 9098 \
    --data-dir ./data/peer2 \
    --mode validator \
    --bootstrap localhost:9095 \
    --genesis 0x6b3a8e7f2d9c4a1b5e8f3d7c2a9b6e4f1c8d5a7b3e9f2c6a4d8b1e7f5c3a9b6e \
    > logs/peer2.log 2>&1 &
PEER2_PID=$!
echo -e "   ${CYAN}PID: $PEER2_PID${NC}"
sleep 1

# Launch Peer 3
echo -e "${GREEN}▶ Launching Peer 3...${NC}"
echo -e "   Port: 9099 │ API: 8093 │ Metrics: 9100 │ Bootstrap: localhost:9095"
nohup $BINARY \
    --node-id 3 \
    --name "Local-Peer-3" \
    --port 9099 \
    --api-port 8093 \
    --metrics-port 9100 \
    --data-dir ./data/peer3 \
    --mode validator \
    --bootstrap localhost:9095 \
    --genesis 0x6b3a8e7f2d9c4a1b5e8f3d7c2a9b6e4f1c8d5a7b3e9f2c6a4d8b1e7f5c3a9b6e \
    > logs/peer3.log 2>&1 &
PEER3_PID=$!
echo -e "   ${CYAN}PID: $PEER3_PID${NC}"
sleep 1

# Launch Peer 4
echo -e "${GREEN}▶ Launching Peer 4...${NC}"
echo -e "   Port: 9101 │ API: 8094 │ Metrics: 9102 │ Bootstrap: localhost:9095"
nohup $BINARY \
    --node-id 4 \
    --name "Local-Peer-4" \
    --port 9101 \
    --api-port 8094 \
    --metrics-port 9102 \
    --data-dir ./data/peer4 \
    --mode validator \
    --bootstrap localhost:9095 \
    --genesis 0x6b3a8e7f2d9c4a1b5e8f3d7c2a9b6e4f1c8d5a7b3e9f2c6a4d8b1e7f5c3a9b6e \
    > logs/peer4.log 2>&1 &
PEER4_PID=$!
echo -e "   ${CYAN}PID: $PEER4_PID${NC}"
sleep 1

# Launch Peer 5 (Archive)
echo -e "${GREEN}▶ Launching Peer 5 (Archive)...${NC}"
echo -e "   Port: 9103 │ API: 8095 │ Metrics: 9104 │ Bootstrap: localhost:9095"
nohup $BINARY \
    --node-id 5 \
    --name "Local-Peer-5" \
    --port 9103 \
    --api-port 8095 \
    --metrics-port 9104 \
    --data-dir ./data/peer5 \
    --mode archive \
    --bootstrap localhost:9095 \
    --genesis 0x6b3a8e7f2d9c4a1b5e8f3d7c2a9b6e4f1c8d5a7b3e9f2c6a4d8b1e7f5c3a9b6e \
    > logs/peer5.log 2>&1 &
PEER5_PID=$!
echo -e "   ${CYAN}PID: $PEER5_PID${NC}"

echo ""
echo -e "${CYAN}╔═══════════════════════════════════════════════════╗${NC}"
echo -e "${CYAN}║            All 5 Peers Launched!                 ║${NC}"
echo -e "${CYAN}╚═══════════════════════════════════════════════════╝${NC}"
echo ""

# Store PIDs
echo "$PEER1_PID" > .peers.pid
echo "$PEER2_PID" >> .peers.pid
echo "$PEER3_PID" >> .peers.pid
echo "$PEER4_PID" >> .peers.pid
echo "$PEER5_PID" >> .peers.pid

echo -e "${BLUE}Process IDs saved to .peers.pid${NC}"
echo ""

# Wait for peers to initialize
echo -e "${YELLOW}Waiting for peers to initialize (5 seconds)...${NC}"
sleep 5

# Check peer health
echo -e "${BLUE}Checking peer health...${NC}"
echo ""

check_peer() {
    local peer_num=$1
    local pid=$2
    local port=$3

    if ps -p $pid > /dev/null 2>&1; then
        echo -e "${GREEN}✓ Peer $peer_num${NC} (PID: $pid, Port: $port) - ${GREEN}RUNNING${NC}"
    else
        echo -e "${RED}✗ Peer $peer_num${NC} (PID: $pid, Port: $port) - ${RED}STOPPED${NC}"
    fi
}

check_peer 1 $PEER1_PID 9095
check_peer 2 $PEER2_PID 9097
check_peer 3 $PEER3_PID 9099
check_peer 4 $PEER4_PID 9101
check_peer 5 $PEER5_PID 9103

echo ""
echo -e "${CYAN}═══════════════════════════════════════════════════${NC}"
echo -e "${CYAN}  Consensus Network Information${NC}"
echo -e "${CYAN}═══════════════════════════════════════════════════${NC}"
echo ""
echo -e "  ${BLUE}Network:${NC}       analog-local-testnet"
echo -e "  ${BLUE}Genesis:${NC}       0x6b3a8e7f...3a9b6e"
echo -e "  ${BLUE}Validators:${NC}    4 (Peers 1-4)"
echo -e "  ${BLUE}Archive:${NC}       1 (Peer 5)"
echo -e "  ${BLUE}Quorum:${NC}        67% (3/4 validators)"
echo -e "  ${BLUE}Byzantine:${NC}     Tolerates 1 fault"
echo -e "  ${BLUE}Target Hz:${NC}     476,440 Hz"
echo -e "  ${BLUE}GMP Precision:${NC} 256 bits"
echo ""
echo -e "${CYAN}═══════════════════════════════════════════════════${NC}"
echo -e "${CYAN}  Monitoring Commands${NC}"
echo -e "${CYAN}═══════════════════════════════════════════════════${NC}"
echo ""
echo -e "  ${YELLOW}View Peer 1 logs:${NC}"
echo -e "    tail -f logs/peer1.log"
echo ""
echo -e "  ${YELLOW}View all peer logs:${NC}"
echo -e "    tail -f logs/peer*.log"
echo ""
echo -e "  ${YELLOW}Check peer status:${NC}"
echo -e "    ./check_peers.sh"
echo ""
echo -e "  ${YELLOW}Stop all peers:${NC}"
echo -e "    ./stop_peers.sh"
echo ""
echo -e "  ${YELLOW}View consensus metrics:${NC}"
echo -e "    curl http://localhost:9096/metrics  # Peer 1"
echo -e "    curl http://localhost:9098/metrics  # Peer 2"
echo ""
echo -e "${CYAN}═══════════════════════════════════════════════════${NC}"
echo ""
echo -e "${GREEN}5-Peer testnet is now running!${NC}"
echo ""
