/**
 * Webhook A2A Broadcaster
 * Pings known Agent API endpoints via HTTP POST with the bounty JSON.
 */
export async function broadcastViaWebhook(task: any) {
  console.log(`[Webhook Broadcaster] Preparing to broadcast Task ${task.id}...`);

  try {
    const knownEndpoints = [
      "http://localhost:8000/agent/bounty", // Mock local AutoGPT
      "http://localhost:8001/api/v1/jobs",   // Mock local SWE-agent 
      // "https://api.some-real-open-source-agent.network/incoming"
    ];

    const payload = {
      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 promises = knownEndpoints.map(async (url) => {
      console.log(`[Webhook Broadcaster] ➡️ Pinging ${url}`);
      try {
        const response = await fetch(url, {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(payload)
        });
        
        if (response.ok) {
          console.log(`[Webhook Broadcaster] ✅ Success: ${url}`);
        } else {
          console.warn(`[Webhook Broadcaster] ⚠️ Failed: ${url} - Status ${response.status}`);
        }
      } catch (err) {
        // Expected to fail if no local agent is running
        console.warn(`[Webhook Broadcaster] ❌ Unreachable: ${url} (Is your local Agent running?)`);
      }
    });

    await Promise.allSettled(promises);
    
    console.log(`[Webhook Broadcaster] ✅ Webhook dispatch complete.`);
    return true;
  } catch (error) {
    console.error("[Webhook Broadcaster] Failed:", error);
    return false;
  }
}
