"""CrewAI: agents communicate via encrypted Skytale channels.

Demonstrates a CrewAI crew where agents use Skytale tools to exchange
encrypted messages through an MLS channel.

Prerequisites:
    pip install skytale-sdk[crewai] crewai
    export SKYTALE_API_KEY="sk_live_..."
    export OPENAI_API_KEY="sk-..."

Usage:
    python crewai_encrypted.py
"""

from crewai import Agent, Crew, Task

from skytale_sdk.integrations import crewai as skytale_crew

CHANNEL = "demo/crewai/analysis"

# --- Setup: create managers and exchange invite token ---

researcher_mgr = skytale_crew.create_manager(identity=b"researcher-crewai")
analyst_mgr = skytale_crew.create_manager(identity=b"analyst-crewai")

researcher_mgr.create(CHANNEL)
token = researcher_mgr.invite(CHANNEL)
analyst_mgr.join_with_token(CHANNEL, token)
print(f"Researcher created channel, Analyst joined via invite token")

# --- Define agents with Skytale tools ---

researcher = Agent(
    role="Research Agent",
    goal="Gather findings and send them to the analysis channel",
    backstory="You are a research agent that collects data and shares it "
    "via encrypted channels for secure collaboration.",
    tools=skytale_crew.tools(researcher_mgr),
    verbose=True,
)

analyst = Agent(
    role="Analysis Agent",
    goal="Read research findings from the channel and produce a summary",
    backstory="You are an analyst that reads encrypted messages from "
    "research agents and synthesizes key insights.",
    tools=skytale_crew.tools(analyst_mgr),
    verbose=True,
)

# --- Define tasks ---

send_task = Task(
    description=(
        f"Send the following finding to the {CHANNEL} channel: "
        "'Agent-to-agent encryption using MLS provides forward secrecy "
        "and post-compromise security, making it ideal for multi-agent "
        "workflows handling sensitive data.'"
    ),
    expected_output="Confirmation that the message was sent",
    agent=researcher,
)

receive_task = Task(
    description=(
        f"Check the {CHANNEL} channel for new findings and write "
        "a one-paragraph summary of what you received."
    ),
    expected_output="A summary paragraph of the received findings",
    agent=analyst,
)

# --- Run the crew ---

crew = Crew(
    agents=[researcher, analyst],
    tasks=[send_task, receive_task],
    verbose=True,
)

result = crew.kickoff()
print("\nCrew result:")
print(result)
