#!/bin/bash

# Export OpenAPI specification from running API
# This script starts the API, exports the Swagger JSON, and cleans up

set -e  # Exit on error

echo "🚀 Starting Codex API..."

# Start the API in background
cd "$(dirname "$0")"
dotnet run --project Codex.Api/Codex.Api.csproj > /dev/null 2>&1 &
API_PID=$!

echo "⏳ Waiting for API to start (PID: $API_PID)..."

# Wait for API to be ready (max 30 seconds)
MAX_ATTEMPTS=30
ATTEMPT=0
while [ $ATTEMPT -lt $MAX_ATTEMPTS ]; do
    if curl -f -s http://localhost:5246/swagger/v1/swagger.json > /dev/null 2>&1; then
        echo "✅ API is ready!"
        break
    fi
    ATTEMPT=$((ATTEMPT + 1))
    echo "   Attempt $ATTEMPT/$MAX_ATTEMPTS..."
    sleep 1
done

# Check if process is still running
if ! kill -0 $API_PID 2>/dev/null; then
    echo "❌ API failed to start"
    exit 1
fi

# Check if we timed out
if [ $ATTEMPT -eq $MAX_ATTEMPTS ]; then
    echo "❌ API did not respond within 30 seconds"
    kill $API_PID 2>/dev/null || true
    exit 1
fi

echo "📥 Downloading OpenAPI specification..."

# Export the swagger.json from HTTP endpoint (HTTPS not enabled in development)
if curl -f -s http://localhost:5246/swagger/v1/swagger.json -o docs/openapi.json; then
    echo "✅ OpenAPI spec exported to docs/openapi.json"

    # Pretty print some stats
    ENDPOINTS=$(grep -o '"paths"' docs/openapi.json | wc -l)
    FILE_SIZE=$(du -h docs/openapi.json | cut -f1)
    echo "📊 Specification size: $FILE_SIZE"
    echo "📊 Documented: $(grep -o '"/api/' docs/openapi.json | wc -l | tr -d ' ') endpoint(s)"
else
    echo "❌ Failed to download OpenAPI spec"
    kill $API_PID 2>/dev/null || true
    exit 1
fi

echo "🛑 Stopping API..."
kill $API_PID 2>/dev/null || true

# Wait for process to terminate
wait $API_PID 2>/dev/null || true

echo "✨ Done! OpenAPI specification is ready at docs/openapi.json"
echo ""
echo "📝 Remember to:"
echo "   1. Review the generated openapi.json"
echo "   2. Update CHANGELOG.md if there are breaking changes"
echo "   3. Notify frontend teams of API updates"
