#!/bin/bash
# Quick debug script to test idempotency extraction

GATEWAY_URL="${TEST_SERVER_URL:-http://localhost:3000}"
API_KEY="${TEST_API_KEY:-test-key-ce67dabb0d4e27e3d72877c921b89cae}"

generate_uuid() {
    if command -v uuidgen > /dev/null 2>&1; then
        uuidgen
    else
        cat /proc/sys/kernel/random/uuid 2>/dev/null || \
        echo "$(od -x /dev/urandom | head -1 | awk '{OFS="-"; print $2$3,$4,$5,$6,$7$8$9}' | tr '[:upper:]' '[:lower:]')"
    fi
}

echo "Testing idempotency extraction..."
IDEMPOTENCY_KEY=$(generate_uuid)
echo "Idempotency key: $IDEMPOTENCY_KEY"

IDEMPOTENT_RESPONSE=$(curl -s --max-time 5 -X POST "$GATEWAY_URL/api/runs" \
    -H "x-api-key: $API_KEY" \
    -H "Idempotency-Key: $IDEMPOTENCY_KEY" \
    -H "Content-Type: application/json" \
    -d '{"name":"Idempotency Test","input":{"test":"idempotency"}}' 2>&1)

echo "Response length: ${#IDEMPOTENT_RESPONSE}"
echo "First 300 chars: ${IDEMPOTENT_RESPONSE:0:300}"

FIRST_RUN_ID=$(echo "$IDEMPOTENT_RESPONSE" | grep -o '"run":{[^}]*"id":"[^"]*' | grep -o '"id":"[^"]*' | cut -d'"' -f4 | head -1)
if [ -z "$FIRST_RUN_ID" ]; then
    FIRST_RUN_ID=$(echo "$IDEMPOTENT_RESPONSE" | grep -o '"id":"[a-f0-9-]\{36\}' | cut -d'"' -f4 | head -1)
fi

echo "FIRST_RUN_ID: '$FIRST_RUN_ID'"
echo "Is FIRST_RUN_ID set? $([ -n "$FIRST_RUN_ID" ] && echo "YES" || echo "NO")"

RESPONSE_LEN=${#IDEMPOTENT_RESPONSE}
HAS_SUCCESS=$(echo "$IDEMPOTENT_RESPONSE" | grep -c '"success"' || echo "0")
HAS_RUN=$(echo "$IDEMPOTENT_RESPONSE" | grep -c '"run"' || echo "0")

echo "Response length: $RESPONSE_LEN"
echo "Has 'success': $HAS_SUCCESS"
echo "Has 'run': $HAS_RUN"

