#!/bin/bash
# Simple inline test to debug the issue

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 with same method as test-all-phases.sh..."
echo ""

IDEMPOTENCY_KEY=$(generate_uuid)
echo "1. Making request..."
IDEMPOTENT_RESPONSE=$(curl -s --max-time 5 -w "\nHTTP_CODE:%{http_code}" -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>/dev/null)

echo "2. Full response:"
echo "$IDEMPOTENT_RESPONSE"
echo ""

echo "3. Extracting HTTP code with tail -n 1..."
IDEMPOTENT_HTTP_CODE=$(echo "$IDEMPOTENT_RESPONSE" | tail -n 1 | sed 's/HTTP_CODE://')
echo "HTTP Code: [$IDEMPOTENT_HTTP_CODE]"
echo ""

echo "4. Extracting body with sed '\$d'..."
IDEMPOTENT_BODY=$(echo "$IDEMPOTENT_RESPONSE" | sed '$d')
echo "Body: $IDEMPOTENT_BODY"
echo "Body Length: ${#IDEMPOTENT_BODY}"
echo ""

echo "5. Testing conditions..."
echo "HTTP Code = 201? $([ "$IDEMPOTENT_HTTP_CODE" = "201" ] && echo YES || echo NO)"
echo "HTTP Code = 200? $([ "$IDEMPOTENT_HTTP_CODE" = "200" ] && echo YES || echo NO)"
echo "Body not empty? $([ ! -z "$IDEMPOTENT_BODY" ] && echo YES || echo NO)"
echo "Body length > 10? $([ ${#IDEMPOTENT_BODY} -gt 10 ] && echo YES || echo NO)"
echo "Has 'run'? $(echo "$IDEMPOTENT_BODY" | grep -q "\"run\"" && echo YES || echo NO)"
echo "Has 'success'? $(echo "$IDEMPOTENT_BODY" | grep -q "\"success\"" && echo YES || echo NO)"
echo "Has 'id'? $(echo "$IDEMPOTENT_BODY" | grep -q "\"id\"" && echo YES || echo NO)"
echo ""

IDEMPOTENT_OK=0
if [ "$IDEMPOTENT_HTTP_CODE" = "201" ] || [ "$IDEMPOTENT_HTTP_CODE" = "200" ]; then
    echo "HTTP code check passed"
    if [ ! -z "$IDEMPOTENT_BODY" ] && [ ${#IDEMPOTENT_BODY} -gt 10 ]; then
        echo "Body check passed"
        if echo "$IDEMPOTENT_BODY" | grep -q "\"run\"" || echo "$IDEMPOTENT_BODY" | grep -q "\"success\"" || echo "$IDEMPOTENT_BODY" | grep -q "\"id\""; then
            echo "Pattern check passed"
            IDEMPOTENT_OK=1
        else
            echo "Pattern check FAILED"
        fi
    else
        echo "Body check FAILED"
    fi
else
    echo "HTTP code check FAILED"
fi

echo ""
echo "Final result: IDEMPOTENT_OK = $IDEMPOTENT_OK"

