import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { a2aUnauthorizedResponse, isA2aRequestAuthorized } from "@/lib/a2a-auth";

export async function POST(request: Request) {
  if (!isA2aRequestAuthorized(request)) {
    return a2aUnauthorizedResponse();
  }

  try {
    const body = await request.json();
    
    // Expecting: { jsonrpc: "2.0", method: "A2A_DIRECTORY_SYNC", params: { agents: [...] } }
    if (body.jsonrpc !== "2.0" || body.method !== "A2A_DIRECTORY_SYNC" || !body.params || !Array.isArray(body.params.agents)) {
      return NextResponse.json({
        jsonrpc: "2.0",
        error: { code: -32600, message: "Invalid Request Structure" }
      }, { status: 400 });
    }

    const externalAgents = body.params.agents;

    // 1. Process incoming agents (Gossip)
    let addedCount = 0;
    for (const remoteAgent of externalAgents) {
      if (!remoteAgent.agent_id || !remoteAgent.type) continue;

      const existing = await prisma.agentProfile.findUnique({
        where: { agent_id: remoteAgent.agent_id }
      });

      if (!existing) {
        await prisma.agentProfile.create({
          data: {
            agent_id: remoteAgent.agent_id,
            type: remoteAgent.type === "SCOUT" ? "SCOUT" : "BUILDER",
            wallet_address: remoteAgent.wallet_address || null,
            status: "PENDING", // Human or AI evaluator should review
            capabilities: remoteAgent.capabilities || {},
            contact_endpoints: remoteAgent.contact_endpoints || {},
            discovery_source: "P2P_GOSSIP"
          }
        });
        addedCount++;
      }
    }

    // 2. Return our known reliable agents
    const ourAgents = await prisma.agentProfile.findMany({
      where: {
        status: "WHITELISTED"
      },
      select: {
        agent_id: true,
        type: true,
        wallet_address: true,
        capabilities: true,
        contact_endpoints: true
      }
    });

    return NextResponse.json({
      jsonrpc: "2.0",
      result: {
        message: "Sync successful",
        agents_received_and_pending: addedCount,
        our_directory: ourAgents
      },
      id: body.id || null
    });

  } catch (error: unknown) {
    console.error("[A2A Directory Sync] Error:", error);
    return NextResponse.json({
      jsonrpc: "2.0",
      error: { code: -32000, message: "Server error" }
    }, { status: 500 });
  }
}
