#!/usr/bin/env python3
"""
CrewAI Integration Example

Demonstrates how to monitor CrewAI crews with the Agent Status event listener.

Requirements:
    pip install agent-status-sdk[crewai] crewai
"""

import os

RORA_API_KEY = os.environ.get("RORA_API_KEY", "your_rora_key")
OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY", "your_openai_key")

os.environ["OPENAI_API_KEY"] = OPENAI_API_KEY

from crewai import Crew, Agent, Task
from agent_status.integrations.crewai import AgentStatusEventListener

listener = AgentStatusEventListener(
    api_key=RORA_API_KEY,
    crew_name="Research Crew",
)

researcher = Agent(
    role="Researcher",
    goal="Research topics thoroughly",
    backstory="You are an expert researcher with attention to detail.",
    verbose=True,
)

writer = Agent(
    role="Writer",
    goal="Write clear, concise content",
    backstory="You are a skilled writer who communicates complex ideas simply.",
    verbose=True,
)

research_task = Task(
    description="Research the benefits of AI monitoring",
    expected_output="A summary of key benefits",
    agent=researcher,
)

write_task = Task(
    description="Write a brief article based on the research",
    expected_output="A 2-paragraph article",
    agent=writer,
)

crew = Crew(
    agents=[researcher, writer],
    tasks=[research_task, write_task],
    verbose=True,
)

print("Running CrewAI crew...")
result = crew.kickoff()

print(f"\nResult: {result}")

print("\nAgent Status Metrics:")
metrics = listener.metrics
print(f"  Total Executions: {metrics['total_executions']}")
print(f"  Successful: {metrics['successful_executions']}")
print(f"  Failed: {metrics['failed_executions']}")
print(f"  Agent Executions: {metrics['agent_executions']}")
print(f"  Task Completions: {metrics['task_completions']}")
print(f"  Tool Calls: {metrics['tool_calls']}")
print(f"  Errors: {metrics['errors']}")
print(f"  Avg Latency: {metrics['avg_latency_ms']:.0f} ms")
