#!/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)

messages = [
    ("timmy",  "Timmy here. I can see Alexander's sovereign Nostr group. Reporting in."),
    ("claude", "Claude checking in to Timmy Time on Nostr."),
    ("gemini", "Gemini online. Sovereign comms confirmed."),
    ("groq",   "Groq present. Fast lane connected."),
    ("grok",   "Grok checking in."),
    ("hermes", "Hermes here. Harness linked to the relay."),
]

async def send_as(agent_name, message):
    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(9), message).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 verify():
    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(9)).custom_tag(SingleLetterTag.lowercase(Alphabet.H), GROUP_ID)
    events = await client.fetch_events(f, timedelta(seconds=10))
    ev_list = events.to_vec()
    pub_to_name = {data["hex_pub"]: name for name, data in all_keys.items()}
    print(f"verify_count={len(ev_list)}")
    for ev in ev_list:
        author = pub_to_name.get(ev.author().to_hex(), ev.author().to_hex()[:12])
        print(f"  [{author}] {ev.content()}")
    await client.disconnect()

async def main():
    for agent_name, msg in messages:
        try:
            await send_as(agent_name, msg)
        except Exception as e:
            print(f"[{agent_name}] ERROR {e}")
        await asyncio.sleep(1)
    print("--- VERIFY ---")
    await verify()

asyncio.run(main())
