#!/usr/bin/env python3
import json
import asyncio
from datetime import timedelta
from nostr_sdk import Keys, Client, NostrSigner, Filter, Kind, EventBuilder, Tag, RelayUrl, SingleLetterTag, Alphabet

RELAY_URL = "ws://143.198.27.163:2929"
KEYS_FILE = "/Users/apayne/.timmy/nostr/agent_keys.json"
GROUP_ID = "b082d1"

with open(KEYS_FILE) as f:
    all_keys = json.load(f)

agents = ["timmy","claude","gemini","groq","grok","hermes"]

async def send_join(agent_name):
    keys = Keys.parse(all_keys[agent_name]["hex_sec"])
    signer = NostrSigner.keys(keys)
    client = Client(signer)
    await client.add_relay(RelayUrl.parse(RELAY_URL))
    await client.connect()
    await asyncio.sleep(1)
    builder = EventBuilder(Kind(9021), "request to join").tags([Tag.parse(["h", GROUP_ID])])
    result = await client.send_event_builder(builder)
    print(f"[{agent_name}] id={result.id.to_hex()[:16]} success={list(result.success)} failed={dict(result.failed)}")
    await client.disconnect()

async def query_join_requests():
    keys = Keys.parse(all_keys["timmy"]["hex_sec"])
    signer = NostrSigner.keys(keys)
    client = Client(signer)
    await client.add_relay(RelayUrl.parse(RELAY_URL))
    await client.connect()
    await asyncio.sleep(1)
    f = Filter().kind(Kind(9021)).custom_tag(SingleLetterTag.lowercase(Alphabet.H), GROUP_ID)
    events = await client.fetch_events(f, timedelta(seconds=10))
    print(f"join_request_count={len(events.to_vec())}")
    for ev in events.to_vec():
        print(ev.author().to_hex(), ev.content())
    await client.disconnect()

async def main():
    for a in agents:
        await send_join(a)
        await asyncio.sleep(1)
    print('--- QUERY ---')
    await query_join_requests()

asyncio.run(main())
