#!/bin/bash
# Quick Consensus Test: Fast verification (only to evolution 1000)

echo "════════════════════════════════════════════════════════════"
echo "  V4.2 QUICK CONSENSUS TEST"
echo "  Testing evolution 100, 500, 1000 (< 10 seconds each run)"
echo "════════════════════════════════════════════════════════════"
echo ""

# Run codec twice, capture checkpoints up to 1000
echo "Run 1: Capturing checkpoints..."
timeout 15 ./analog_codec_v42 2>&1 | grep -E "Evolution: (100|500|1000) " > /tmp/quick_run1.txt

echo "Run 2: Capturing checkpoints..."
timeout 15 ./analog_codec_v42 2>&1 | grep -E "Evolution: (100|500|1000) " > /tmp/quick_run2.txt

echo ""
echo "════════════════════════════════════════════════════════════"
echo "COMPARISON:"
echo "════════════════════════════════════════════════════════════"
echo ""

# Compare each checkpoint
TOTAL=0
PASSED=0
for CHECKPOINT in 100 500 1000; do
    RUN1=$(grep "Evolution: $CHECKPOINT " /tmp/quick_run1.txt | head -1)
    RUN2=$(grep "Evolution: $CHECKPOINT " /tmp/quick_run2.txt | head -1)
    TOTAL=$((TOTAL + 1))

    if [ -z "$RUN1" ] || [ -z "$RUN2" ]; then
        echo "⚠️  Evolution $CHECKPOINT: NOT CAPTURED"
        echo "    (Run timed out or grep missed it)"
    elif [ "$RUN1" == "$RUN2" ]; then
        echo "✅ Evolution $CHECKPOINT: IDENTICAL"
        PASSED=$((PASSED + 1))
        # Extract just the key metrics
        OMEGA=$(echo "$RUN1" | grep -oP 'Ω: \K[0-9.]+')
        PHASE=$(echo "$RUN1" | grep -oP 'Phase: \K\w+')
        KG=$(echo "$RUN1" | grep -oP 'K/γ: \K[0-9.]+')
        echo "    Phase: $PHASE, K/γ: $KG:1, Ω: $OMEGA"
    else
        echo "❌ Evolution $CHECKPOINT: DIVERGED!"
        echo "    RUN1: $RUN1"
        echo "    RUN2: $RUN2"
    fi
    echo ""
done

echo "════════════════════════════════════════════════════════════"
echo "RESULT: $PASSED/$TOTAL checkpoints identical"
if [ "$PASSED" -eq "$TOTAL" ]; then
    echo "✅ CONSENSUS VERIFIED - V4.2 achieves bit-exact reproducibility!"
else
    echo "⚠️  Some checkpoints failed - check output above"
fi
echo "════════════════════════════════════════════════════════════"
