#!/bin/bash
# Test orchestrator workflow - complete test
# This script tests the full orchestrator flow end-to-end

set -e

echo "🧪 Testing TicketOrchestrator workflow..."
echo ""

# Create ticket with tool already assigned
echo "1️⃣ Creating ticket with aider assignment..."
TICKET=$(curl -s -X POST http://localhost:5001/dashboard/tickets \
  -H "Content-Type: application/json" \
  -d '{"task":"Create greeting module with hello() function","type":"feature","priority":"medium","title":"Greeting Module","tool":"aider","files":["greeting.py"]}')
TICKET_ID=$(echo "$TICKET" | python3 -c "import sys,json; print(json.load(sys.stdin)['id'])")
echo "   ✅ Created ticket: $TICKET_ID"

# Check initial status
echo ""
echo "2️⃣ Checking initial status..."
curl -s http://localhost:5001/dashboard/tickets/$TICKET_ID | python3 -c "import sys,json; d=json.load(sys.stdin); print(f\"   Status: {d['status']}\")"

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

# Check job status
echo ""
echo "4️⃣ Checking job status..."
curl -s http://localhost:5001/dashboard/tools/queue/jobs | python3 -c "
import sys, json
d = json.load(sys.stdin)
jobs = d.get('jobs', [])
for j in jobs:
    if '$TICKET_ID' in str(j.get('ticket_id', '')):
        print(f\"   Job: {j.get('id', '?')[:8]}... Status: {j.get('status')}\")
" || echo "   No job found for ticket"

# Check final ticket status and comments
echo ""
echo "5️⃣ Checking final ticket status and comments..."
curl -s http://localhost:5001/dashboard/tickets/$TICKET_ID | python3 -c "
import sys, json
d = json.load(sys.stdin)
print(f\"   Final status: {d['status']}\")
print(f\"   Comments: {len(d.get('comments', []))}\")
for i, c in enumerate(d.get('comments', []), 1):
    author = c.get('author', '?')
    content = c.get('content', '')[:60]
    print(f\"   Comment {i}: [{author}] {content}...\")
"

echo ""
echo "✅ Test completed!"
