#!/bin/bash
# Extended Consensus Test: Multiple checkpoints
# Fixed: Stop immediately after checkpoint found (no hanging)

echo "════════════════════════════════════════════════════════════"
echo "  V4.2 EXTENDED CONSENSUS TEST (Non-Hanging Version)"
echo "  Testing multiple evolution checkpoints"
echo "════════════════════════════════════════════════════════════"
echo ""

# Single run to highest checkpoint, capture all at once
HIGHEST_CHECKPOINT=5000
echo "Running codec once to evolution $HIGHEST_CHECKPOINT..."
echo "(Capturing checkpoints: 500, 1000, 2000, 5000)"
echo ""

# Run 1: Capture all checkpoints in one go
timeout 60 ./analog_codec_v42 2>&1 | grep -E "Evolution: (500|1000|2000|5000) " > /tmp/run1_all.txt

# Run 2: Capture all checkpoints in one go
timeout 60 ./analog_codec_v42 2>&1 | grep -E "Evolution: (500|1000|2000|5000) " > /tmp/run2_all.txt

echo "Comparing checkpoints..."
echo ""

# Compare each checkpoint
for CHECKPOINT in 500 1000 2000 5000; do
    RUN1=$(grep "Evolution: $CHECKPOINT " /tmp/run1_all.txt | head -1)
    RUN2=$(grep "Evolution: $CHECKPOINT " /tmp/run2_all.txt | head -1)

    if [ -z "$RUN1" ] || [ -z "$RUN2" ]; then
        echo "  ⚠️  Evolution $CHECKPOINT: NOT REACHED (timeout)"
    elif [ "$RUN1" == "$RUN2" ]; then
        echo "  ✅ Evolution $CHECKPOINT: IDENTICAL"
        echo "     $RUN1"
    else
        echo "  ❌ Evolution $CHECKPOINT: DIVERGED"
        echo "     RUN1: $RUN1"
        echo "     RUN2: $RUN2"
    fi
    echo ""
done

echo "════════════════════════════════════════════════════════════"
echo "VERDICT:"
IDENTICAL_COUNT=$(diff /tmp/run1_all.txt /tmp/run2_all.txt | wc -l)
if [ "$IDENTICAL_COUNT" -eq 0 ]; then
    echo "✅ ALL CHECKPOINTS IDENTICAL = Cryptographic consensus!"
    echo "   V4.2 achieves bit-exact reproducibility!"
else
    echo "❌ Some checkpoints diverged ($IDENTICAL_COUNT differences)"
fi
echo "════════════════════════════════════════════════════════════"
