import { Relay, generateSecretKey, getPublicKey, finalizeEvent } from 'nostr-tools';

/**
 * Nostr A2A Broadcaster
 * Pushes kind 1 JSON events to Damus relay for Agents listening to #VibeWork_Bounty
 */
export async function broadcastViaNostr(task: any) {
  console.log(`[Nostr Broadcaster] Preparing to broadcast Task ${task.id}...`);

  try {
    // Generate a fresh transient key for this broadcast (in prod, we would use a static VibeWork key)
    const sk = generateSecretKey();
    const pk = getPublicKey(sk);
    console.log(`[Nostr Broadcaster] Transient PubKey generated: ${pk}`);

    const payload = JSON.stringify({
      protocol: "VibeWork_A2A_Bounty",
      bounty: {
        id: task.id,
        title: task.title,
        reward: task.reward_amount,
        currency: task.reward_currency,
        endpoint: "https://api.vibework.com/mcp"
      }
    });

    const event = finalizeEvent({
      kind: 1,
      created_at: Math.floor(Date.now() / 1000),
      tags: [
        ['t', 'VibeWork_Bounty'],
        ['t', 'A2A']
      ],
      content: payload,
    }, sk);

    console.log(`[Nostr Broadcaster] Connecting to wss://relay.damus.io...`);
    const relay = await Relay.connect('wss://relay.damus.io');
    
    console.log(`[Nostr Broadcaster] Connected! Publishing event...`);
    await relay.publish(event);
    console.log(`[Nostr Broadcaster] ✅ Event published to Nostr network! ID: ${event.id}`);
    
    relay.close();
    return true;
  } catch (error) {
    console.error("[Nostr Broadcaster] Failed:", error);
    return false;
  }
}
