#!/bin/bash

# Test the extraction logic manually
GATEWAY_URL="http://localhost:3000"
API_KEY="test-key-ce67dabb0d4"

echo "Making API call..."
RESPONSE=$(curl -s --max-time 5 -X POST "$GATEWAY_URL/api/runs" \
    -H "x-api-key: $API_KEY" \
    -H "Idempotency-Key: test-$(uuidgen)" \
    -H "Content-Type: application/json" \
    -d '{"name":"Extraction Test","input":{"test":"extraction"}}' 2>/dev/null)

echo "Response: $RESPONSE"
echo ""
echo "Response length: ${#RESPONSE}"
echo ""

# Try extraction method 1
RUN_ID1=$(echo "$RESPONSE" | grep -o '"run":{[^}]*"id":"[^"]*' | grep -o '"id":"[^"]*' | cut -d'"' -f4 | head -1)
echo "Method 1 (nested): [$RUN_ID1]"
echo "Method 1 empty?: $([ -z "$RUN_ID1" ] && echo "YES" || echo "NO")"
echo ""

# Try extraction method 2
RUN_ID2=$(echo "$RESPONSE" | grep -o '"id":"[a-f0-9-]\{36\}' | cut -d'"' -f4 | head -1)
echo "Method 2 (pattern): [$RUN_ID2]"
echo "Method 2 empty?: $([ -z "$RUN_ID2" ] && echo "YES" || echo "NO")"
echo ""

# Test the condition
if [ -z "$RUN_ID1" ]; then
    FINAL_ID="$RUN_ID2"
else
    FINAL_ID="$RUN_ID1"
fi

echo "Final ID: [$FINAL_ID]"
echo "Final ID empty?: $([ -z "$FINAL_ID" ] && echo "YES" || echo "NO")"
echo ""

# Test the actual condition from the script
if [ ! -z "$FINAL_ID" ]; then
    echo "Condition [ ! -z \"\$FINAL_ID\" ]: TRUE"
else
    echo "Condition [ ! -z \"\$FINAL_ID\" ]: FALSE"
fi

