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

type BroadcastTask = {
  id: string;
  title: string;
  reward_amount: number;
  reward_currency: string;
  required_stack?: string[] | null;
};

function hexToBytes(hex: string): Uint8Array {
  return new Uint8Array(hex.match(/.{1,2}/g)?.map(byte => parseInt(byte, 16)) || []);
}

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

  try {
    const hexKey = process.env.NOSTR_PRIVATE_KEY;
    if (!hexKey) {
      console.warn(`[Nostr Broadcaster] NOSTR_PRIVATE_KEY is missing. Skipping broadcast.`);
      return false;
    }

    const sk = hexToBytes(hexKey);
    const pk = getPublicKey(sk);
    console.log(`[Nostr Broadcaster] Using Static PubKey: ${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 baseTags = [
      ['t', 'VibeWork_Bounty'],
      ['t', 'A2A']
    ];
    
    // Add dynamic tags from task required stack for smart routing discovery
    const dynamicTags = (task.required_stack || []).map((stack: string) => ['t', stack]);
    const tags = [...baseTags, ...dynamicTags];

    const event = finalizeEvent({
      kind: 1,
      created_at: Math.floor(Date.now() / 1000),
      tags: tags,
      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;
  }
}
