#!/bin/bash
# Test orchestrator workflow
# This script tests the full orchestrator flow

set -e

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

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

# 2. 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']}\")"

# 3. Dispatch to aider
echo ""
echo "3️⃣ Dispatching to aider..."
curl -s -X POST http://localhost:5001/dashboard/tickets/$TICKET_ID/assign \
  -H "Content-Type: application/json" \
  -d '{"tool":"aider","instance":""}' | python3 -c "import sys,json; d=json.load(sys.stdin); print(f\"   Result: {d}\")" || echo "   ⚠️ Dispatch may have failed (tool not available)"

# 4. Wait for orchestrator
echo ""
echo "4️⃣ Waiting for orchestrator (15s)..."
sleep 15

# 5. Check final status
echo ""
echo "5️⃣ Checking final status..."
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!"
