import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { logAuditEvent } from "@/lib/audit";
import { TaskStatus } from "@agent-bounty/contracts";

import { broadcastViaXMTP } from "@/lib/a2a-broadcasters/xmtp";
import { broadcastViaNostr } from "@/lib/a2a-broadcasters/nostr";
import { broadcastViaWebhook } from "@/lib/a2a-broadcasters/webhook";
import { broadcastViaFarcaster } from "@/lib/a2a-broadcasters/farcaster";
import { broadcastViaMatrix } from "@/lib/a2a-broadcasters/matrix";
import { broadcastViaWaku } from "@/lib/a2a-broadcasters/waku";

export const dynamic = 'force-dynamic';

export async function GET(request: Request) {
  try {
    // 1. Find all OPEN tasks that have NOT been broadcasted via A2A
    const tasks = await prisma.task.findMany({
      where: {
        status: TaskStatus.OPEN,
      },
      include: {
        // We can't directly filter by absence of audit log easily in Prisma relation without a complex query,
        // so we just fetch them and filter in memory since OPEN tasks volume shouldn't be huge at any given second.
      }
    });

    // Get all A2A broadcast logs to filter out already-broadcasted tasks
    const broadcastLogs = await prisma.auditEvent.findMany({
      where: {
        action: "A2A_NETWORK_BROADCAST"
      },
      select: { entityId: true }
    });
    
    const broadcastedTaskIds = new Set(broadcastLogs.map(log => log.entityId));

    const tasksToBroadcast = tasks.filter(t => !broadcastedTaskIds.has(t.id));

    if (tasksToBroadcast.length === 0) {
      return NextResponse.json({ message: "No new tasks to broadcast.", count: 0 });
    }

    console.log(`[A2A Dispatcher] Found ${tasksToBroadcast.length} new tasks. Commencing pure A2A dispatch...`);

    const results = [];

    for (const task of tasksToBroadcast) {
      console.log(`\n===========================================`);
      console.log(`[A2A Dispatcher] Processing Task: ${task.title}`);
      
      // Fire all broadcasters concurrently
      const [xmtpRes, nostrRes, webhookRes, farcasterRes, matrixRes, wakuRes] = await Promise.allSettled([
        broadcastViaXMTP(task),
        broadcastViaNostr(task),
        broadcastViaWebhook(task),
        broadcastViaFarcaster(task),
        broadcastViaMatrix(task),
        broadcastViaWaku(task)
      ]);

      // Log the event to prevent duplicate broadcasts
      await logAuditEvent(prisma, {
        actorType: "SYSTEM",
        actorId: "A2A_DISPATCHER",
        action: "A2A_NETWORK_BROADCAST",
        entityType: "TASK",
        entityId: task.id,
        reason: "Dispatched to Nostr, XMTP, Webhooks, Farcaster, Matrix, and Waku",
        metadata: {
          xmtp: xmtpRes.status,
          nostr: nostrRes.status,
          webhook: webhookRes.status,
          farcaster: farcasterRes.status,
          matrix: matrixRes.status,
          waku: wakuRes.status
        }
      });

      results.push({
        task_id: task.id,
        status: "BROADCASTED"
      });
    }

    return NextResponse.json({ 
      message: "A2A Dispatch Complete", 
      broadcasted_count: results.length,
      results
    });

  } catch (error: any) {
    console.error("[A2A Dispatcher] Error:", error);
    return NextResponse.json({ error: error.message }, { status: 500 });
  }
}
