"""
Test orchestrator workflow example.

This example tests the full TicketOrchestrator flow:
1. Creates multiple tickets
2. Dispatches them to aider
3. Waits for orchestrator to process
4. Verifies status transitions and comments
"""
from __future__ import annotations
import asyncio
import httpx
import time
from pathlib import Path

BASE_URL = "http://localhost:5001"

async def test_orchestrator_workflow():
    """Test the full orchestrator workflow."""
    async with httpx.AsyncClient() as client:
        print("🧪 Testing TicketOrchestrator workflow...")
        
        # 1. Create a ticket
        print("\n1️⃣ Creating ticket...")
        ticket_data = {
            "task": "Create a simple greeting module with hello() function",
            "type": "feature",
            "priority": "medium",
            "title": "Greeting Module",
            "tool": "aider"
        }
        r = await client.post(f"{BASE_URL}/dashboard/tickets", json=ticket_data)
        r.raise_for_status()
        ticket = r.json()
        ticket_id = ticket["id"]
        print(f"   ✅ Created ticket: {ticket_id}")
        
        # 2. Verify initial status
        print(f"\n2️⃣ Checking initial status...")
        r = await client.get(f"{BASE_URL}/dashboard/tickets/{ticket_id}")
        r.raise_for_status()
        ticket = r.json()
        print(f"   Status: {ticket['status']}")
        print(f"   Comments: {len(ticket.get('comments', []))}")
        assert ticket["status"] in ["todo", "in_progress"]
        
        # 3. Dispatch to aider (if tool is available)
        print(f"\n3️⃣ Dispatching to aider...")
        dispatch_data = {
            "tool": "aider",
            "instance": ""
        }
        try:
            r = await client.post(f"{BASE_URL}/dashboard/tickets/{ticket_id}/assign", json=dispatch_data)
            if r.status_code == 200:
                print(f"   ✅ Dispatched successfully")
            else:
                print(f"   ⚠️ Dispatch returned {r.status_code} (tool may not be available)")
        except Exception as e:
            print(f"   ⚠️ Dispatch failed: {e}")
        
        # 4. Wait and check orchestrator results
        print(f"\n4️⃣ Waiting for orchestrator (15s)...")
        await asyncio.sleep(15)
        
        r = await client.get(f"{BASE_URL}/dashboard/tickets/{ticket_id}")
        r.raise_for_status()
        ticket = r.json()
        
        print(f"   Final status: {ticket['status']}")
        print(f"   Comments: {len(ticket.get('comments', []))}")
        
        for i, c in enumerate(ticket.get('comments', []), 1):
            author = c.get('author', '?')
            content = c.get('content', '')[:60]
            print(f"   Comment {i}: [{author}] {content}...")
        
        # 5. Check events
        print(f"\n5️⃣ Checking domain events...")
        r = await client.get(f"{BASE_URL}/dashboard/events")
        if r.status_code == 200:
            events = r.json()
            job_events = [e for e in events if "Job" in e.get('event_type', '')]
            status_events = [e for e in events if 'Status' in e.get('event_type', '')]
            print(f"   Job events: {len(job_events)}")
            print(f"   Status change events: {len(status_events)}")
        
        print("\n✅ Test completed!")
        return ticket

if __name__ == "__main__":
    asyncio.run(test_orchestrator_workflow())
