"""LangGraph: two agents communicate via an encrypted Skytale channel.

Demonstrates binding Skytale tools to a LangGraph ReAct agent so the
LLM can send and receive encrypted messages.

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

Usage:
    python langgraph_encrypted.py
"""

import os
import time

from langchain_openai import ChatOpenAI
from langgraph.prebuilt import create_react_agent

from skytale_sdk.integrations import langgraph as skytale_lg

CHANNEL = "demo/langgraph/research"

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

alice_mgr = skytale_lg.create_manager(identity=b"alice-langgraph")
bob_mgr = skytale_lg.create_manager(identity=b"bob-langgraph")

alice_mgr.create(CHANNEL)
token = alice_mgr.invite(CHANNEL)
bob_mgr.join_with_token(CHANNEL, token)
print(f"Alice created channel, Bob joined via invite token")

# --- Alice's agent: sends a research finding ---

llm = ChatOpenAI(model="gpt-4o")

alice_agent = create_react_agent(llm, skytale_lg.tools(alice_mgr))
alice_agent.invoke(
    {
        "messages": [
            (
                "user",
                f"Send the following research finding to {CHANNEL}: "
                "'Encrypted MLS channels reduce agent communication latency "
                "by 40% compared to HTTPS polling.'",
            )
        ]
    }
)
print("Alice's agent sent finding")

# Give the message time to propagate
time.sleep(2)

# --- Bob's agent: checks for messages ---

bob_agent = create_react_agent(llm, skytale_lg.tools(bob_mgr))
result = bob_agent.invoke(
    {
        "messages": [
            (
                "user",
                f"Check {CHANNEL} for new research findings and summarize them.",
            )
        ]
    }
)

print("\nBob's agent response:")
print(result["messages"][-1].content)
