#!/usr/bin/env python3
"""Diagnose relay connection and NIP-29 group issues."""
import json
import asyncio
from datetime import timedelta
from nostr_sdk import (
    Keys, Client, NostrSigner, Filter, Kind, 
    EventBuilder, Tag, RelayUrl, SingleLetterTag, Alphabet
)

RELAY_URL = "wss://alexanderwhitestone.com/relay"
KEYS_FILE = "/Users/apayne/.timmy/nostr/agent_keys.json"
GROUP_ID = "timmy-time"

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

async def main():
    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(3)
    
    # Query 1: ALL events (no filter)
    print("=== Query 1: All events (any kind) ===")
    f1 = Filter().limit(50)
    events1 = await client.fetch_events(f1, timedelta(seconds=10))
    ev_list1 = events1.to_vec()
    print(f"  Total events found: {len(ev_list1)}")
    for ev in ev_list1[:10]:
        print(f"  kind:{ev.kind().as_u16()} author:{ev.author().to_hex()[:16]} content:{ev.content()[:60]}")
    
    # Query 2: Kind 9 (chat messages) only
    print("\n=== Query 2: Kind 9 (chat messages) ===")
    f2 = Filter().kind(Kind(9)).limit(50)
    events2 = await client.fetch_events(f2, timedelta(seconds=10))
    ev_list2 = events2.to_vec()
    print(f"  Kind 9 events: {len(ev_list2)}")
    for ev in ev_list2[:10]:
        tags = [t.as_vec() for t in ev.tags().to_vec()]
        print(f"  author:{ev.author().to_hex()[:16]} tags:{tags} content:{ev.content()[:60]}")
    
    # Query 3: Kind 39000 (group metadata)
    print("\n=== Query 3: Kind 39000 (group metadata) ===")
    f3 = Filter().kind(Kind(39000)).limit(50)
    events3 = await client.fetch_events(f3, timedelta(seconds=10))
    ev_list3 = events3.to_vec()
    print(f"  Group metadata events: {len(ev_list3)}")
    for ev in ev_list3:
        tags = [t.as_vec() for t in ev.tags().to_vec()]
        print(f"  tags:{tags} content:{ev.content()[:100]}")
    
    # Query 4: Kind 9005 (create-group)
    print("\n=== Query 4: Kind 9005 (create-group) ===")
    f4 = Filter().kind(Kind(9005)).limit(50)
    events4 = await client.fetch_events(f4, timedelta(seconds=10))
    ev_list4 = events4.to_vec()
    print(f"  Create-group events: {len(ev_list4)}")
    
    # Try sending a simple kind 9 NOW and check result
    print("\n=== Test: Send kind 9 message NOW ===")
    tags = [Tag.parse(["h", GROUP_ID])]
    builder = EventBuilder(Kind(9), "diagnostic test message").tags(tags)
    try:
        result = await client.send_event_builder(builder)
        print(f"  Event ID: {result.id.to_hex()}")
        print(f"  Output success: {result.output}")
        # Check what methods are available
        print(f"  Result type: {type(result)}")
        print(f"  Result dir: {[x for x in dir(result) if not x.startswith('_')]}")
    except Exception as e:
        print(f"  ERROR: {e}")
    
    await asyncio.sleep(2)
    
    # Re-query kind 9
    print("\n=== Re-query after send ===")
    f5 = Filter().kind(Kind(9)).limit(50)
    events5 = await client.fetch_events(f5, timedelta(seconds=10))
    ev_list5 = events5.to_vec()
    print(f"  Kind 9 events now: {len(ev_list5)}")
    for ev in ev_list5[:10]:
        tags = [t.as_vec() for t in ev.tags().to_vec()]
        print(f"  content:{ev.content()[:60]} tags:{tags}")
    
    await client.disconnect()

asyncio.run(main())
