"""Group chat: three agents in a single encrypted channel.

Demonstrates adding multiple members to a channel and broadcasting
messages to the whole group.

Usage:
    export SKYTALE_API_KEY="sk_live_..."
    python group_chat.py
"""

import os
import threading
import time
from skytale_sdk import SkytaleClient

RELAY = os.environ.get("SKYTALE_RELAY", "https://relay.skytale.sh:5000")
API_URL = os.environ.get("SKYTALE_API_URL", "https://api.skytale.sh")
API_KEY = os.environ.get("SKYTALE_API_KEY")

kwargs = {}
if API_KEY:
    kwargs["api_key"] = API_KEY
    kwargs["api_url"] = API_URL

# Create three agents
alice = SkytaleClient(RELAY, "/tmp/alice-group", b"alice", **kwargs)
bob = SkytaleClient(RELAY, "/tmp/bob-group", b"bob", **kwargs)
carol = SkytaleClient(RELAY, "/tmp/carol-group", b"carol", **kwargs)

# Alice creates the channel
channel = alice.create_channel("myorg/team/group")
print("Alice created channel: myorg/team/group")

# Add Bob
bob_kp = bob.generate_key_package()
bob_welcome = channel.add_member(bob_kp)
bob_channel = bob.join_channel("myorg/team/group", bob_welcome)
print("Bob joined")

# Add Carol
carol_kp = carol.generate_key_package()
carol_welcome = channel.add_member(carol_kp)
carol_channel = carol.join_channel("myorg/team/group", carol_welcome)
print("Carol joined")


# Each agent listens on a background thread
def listen(ch, name):
    for msg in ch.messages():
        print(f"  {name} received: {bytes(msg).decode()}")


threading.Thread(target=listen, args=(bob_channel, "Bob"), daemon=True).start()
threading.Thread(target=listen, args=(carol_channel, "Carol"), daemon=True).start()

# Alice broadcasts to the group
time.sleep(0.5)
channel.send(b"Hello team! This is Alice.")
print("Alice sent: Hello team! This is Alice.")
time.sleep(1)

# Bob responds
bob_channel.send(b"Hey Alice! Bob here.")
print("Bob sent: Hey Alice! Bob here.")
time.sleep(1)

print("\nDone. All agents communicated in the same encrypted channel.")
