#!/bin/bash
# Orchestrator Test Example
# This example tests the TicketOrchestrator using CLI commands
# which correctly create jobs and trigger orchestrator processing

set -e

echo "🧪 Testing TicketOrchestrator via CLI..."
echo ""

# 1. Create ticket without auto-dispatch (to avoid API issues)
echo "1️⃣ Creating ticket..."
TICKET_OUTPUT=$(proxym ticket add "Create greeting module with hello()" --type feature --priority medium 2>&1)
TICKET_ID=$(echo "$TICKET_OUTPUT" | grep -oE "TKT-[A-Z0-9]+")
echo "   ✅ Created: $TICKET_ID"

# 2. Dispatch via CLI (this works correctly)
echo ""
echo "2️⃣ Dispatching to aider via CLI..."
DISPATCH_OUTPUT=$(proxym dispatch "$TICKET_ID" --tool aider 2>&1)
echo "   $DISPATCH_OUTPUT"

# 3. Wait for job processing
echo ""
echo "3️⃣ Waiting for job to complete (20s)..."
sleep 20

# 4. Check job status
echo ""
echo "4️⃣ Checking job status..."
JOBS_OUTPUT=$(proxym jobs 2>&1)
echo "   Jobs:"
echo "$JOBS_OUTPUT" | grep -E "$TICKET_ID|aider" | head -5 || echo "   (checking via API...)"

# 5. Check ticket status and comments via API
echo ""
echo "5️⃣ Checking ticket status and comments..."
curl -s "http://localhost:5001/dashboard/tickets/$TICKET_ID" 2>/dev/null | python3 -c "
import sys, json
try:
    d = json.load(sys.stdin)
    print(f\"   Status: {d.get('status')}\")
    comments = d.get('comments', [])
    print(f\"   Comments: {len(comments)}\")
    for i, c in enumerate(comments, 1):
        author = c.get('author', '?')
        content = c.get('content', '')[:60]
        print(f\"   {i}. [{author}] {content}...\")
except:
    print('   Could not retrieve ticket data')
" || echo "   API not available"

echo ""
echo "✅ Test completed!"
echo ""
echo "Note: The orchestrator processes JobCompleted/JobFailed events and:"
echo "  - Updates ticket status (todo -> in_review for success)"
echo "  - Adds LLM-generated comments explaining the review"
echo "  - Works correctly with CLI dispatch"
