#!/usr/bin/env python3
"""
Nostr Group Setup — Creates the Timmy Time household group on the relay.
Creates group metadata, posts a test message, logs the group code.
"""
import asyncio, json, secrets

from nostr_sdk import (
    Keys, Client, NostrSigner, Kind, EventBuilder, Tag, RelayUrl
)

RELAY_WS = "ws://127.0.0.1:2929"

def load_nsec(name):
    with open(f"/Users/apayne/.timmy/nostr/agent_keys.json") as f:
        data = json.load(f)
    return data[name]["nsec"], data.get(name, {}).get("npub", "")

async def create_group():
    timmy_nsec, timmy_npub = load_nsec("timmy")
    print(f"Using Timmy: {timmy_npub}")

    keys = Keys.parse(timmy_nsec)
    signer = NostrSigner.keys(keys)
    client = Client(signer)

    # Connect to local relay (forwarded from VPS)
    relay_url = RelayUrl.parse(RELAY_WS)
    await client.add_relay(relay_url)
    await client.connect()

    # Generate group code (NIP-29 uses this as the "h" tag value)
    group_code = secrets.token_hex(4)

    # Group metadata (kind 39000 — replaceable event)
    metadata = json.dumps({
        "name": "Timmy Time",
        "about": "The Timmy Foundation household — sovereign comms for the crew",
    })

    group_def = EventBuilder(Kind(39000), metadata).tags([
        Tag(["d", group_code]),
        Tag(["name", "Timmy Time"]),
        Tag(["about", "The Timmy Foundation household"]),
    ])

    result = await client.send_event_builder(group_def)
    print(f"\nGroup created on relay.alexanderwhitestone.com:2929")
    print(f"  Group code: {group_code}")
    print(f"  Event ID: {result.id.to_hex()}")

    # Post test message as kind 9
    msg = EventBuilder(Kind(9),
        "Timmy speaking: The group is live. Sovereignty and service always."
    ).tags([Tag(["h", group_code])])
    result2 = await client.send_event_builder(msg)
    print(f"  Test message posted: {result2.id.to_hex()[:16]}...")

    # Post second message
    msg2 = EventBuilder(Kind(9),
        "All crew: welcome to sovereign comms. No more Telegram dependency."
    ).tags([Tag(["h", group_code])])
    result3 = await client.send_event_builder(msg2)
    print(f"  Second message posted: {result3.id.to_hex()[:16]}...")

    await client.disconnect()

    # Save group config
    config = {
        "relay": "wss://relay.alexanderwhitestone.com:2929",
        "group_code": group_code,
        "created_by": "timmy",
        "group_name": "Timmy Time",
    }
    with open("/Users/apayne/.timmy/nostr/group_config.json", "w") as f:
        json.dump(config, f, indent=2)
    print(f"\nGroup config saved to ~/.timmy/nostr/group_config.json")

if __name__ == "__main__":
    asyncio.run(create_group())
