#!/bin/bash
# Individual test script for E2E/Workflow feature
# Run this to test only end-to-end workflow

set -e  # Exit on errors

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

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
NC='\033[0m'

PASSED=0
FAILED=0

echo "========================================="
echo "E2E Workflow Tests"
echo "========================================="
echo ""

# Test 1: Create run
echo "--- Test 1: Create run ---"
WORKFLOW_RESPONSE=$(curl -s --max-time 5 -X POST "$GATEWAY_URL/api/runs" \
    -H "x-api-key: $API_KEY" \
    -H "Content-Type: application/json" \
    -d '{"name":"E2E Workflow Test","input":{"test":"workflow"}}' 2>&1)

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

if [ -n "$WORKFLOW_RUN_ID" ]; then
    echo -e "${GREEN}✓ PASSED${NC} - Created run with ID: $WORKFLOW_RUN_ID"
    PASSED=$((PASSED + 1))
else
    echo -e "${RED}✗ FAILED${NC} - Could not extract run ID"
    echo "Response: ${WORKFLOW_RESPONSE:0:200}"
    FAILED=$((FAILED + 1))
    exit 1
fi

# Test 2: Start run
echo ""
echo "--- Test 2: Start run ---"
if [ -n "$WORKFLOW_RUN_ID" ]; then
    START_RESPONSE=$(curl -s --max-time 5 -X POST "$GATEWAY_URL/api/runs/$WORKFLOW_RUN_ID/start" \
        -H "x-api-key: $API_KEY" \
        -H "Content-Type: application/json" \
        -d '{"priority":"normal"}' 2>&1)
    
    if echo "$START_RESPONSE" | grep -q 'queued\|success'; then
        echo -e "${GREEN}✓ PASSED${NC} - Run started successfully"
        PASSED=$((PASSED + 1))
    else
        echo -e "${RED}✗ FAILED${NC} - Start failed"
        echo "Response: ${START_RESPONSE:0:200}"
        FAILED=$((FAILED + 1))
    fi
fi

# Test 3: Get run status
echo ""
echo "--- Test 3: Get run status ---"
if [ -n "$WORKFLOW_RUN_ID" ]; then
    STATUS_RESPONSE=$(curl -s --max-time 5 "$GATEWAY_URL/api/runs/$WORKFLOW_RUN_ID" \
        -H "x-api-key: $API_KEY" 2>&1)
    
    if echo "$STATUS_RESPONSE" | grep -q '"status"'; then
        echo -e "${GREEN}✓ PASSED${NC} - Successfully retrieved run status"
        PASSED=$((PASSED + 1))
    else
        echo -e "${RED}✗ FAILED${NC} - Status check failed"
        echo "Response: ${STATUS_RESPONSE:0:200}"
        FAILED=$((FAILED + 1))
    fi
fi

echo ""
echo "========================================="
echo "E2E Test Summary"
echo "========================================="
echo "Passed: $PASSED"
echo "Failed: $FAILED"
echo ""

if [ $FAILED -eq 0 ]; then
    echo -e "${GREEN}All E2E tests passed!${NC}"
    exit 0
else
    echo -e "${RED}Some tests failed${NC}"
    exit 1
fi

