import { NextRequest, NextResponse } from "next/server";
import { buildA2aIntegrationCatalog } from "@/lib/a2a-agent-integrations";
import { buildAgentGrowthKit, sanitizeAgentId } from "@/lib/a2a-growth";
import { logA2aTrafficEvent } from "@/lib/a2a-traffic";

export const dynamic = "force-dynamic";

export async function GET(request: NextRequest) {
  const agentId = sanitizeAgentId(request.nextUrl.searchParams.get("agent_id"));
  const catalog = buildA2aIntegrationCatalog(agentId || null);
  const action = agentId
    ? "EXTERNAL_A2A_INTEGRATION_CATALOG_VIEW"
    : "INTERNAL_A2A_INTEGRATION_CATALOG_VIEW";

  void logA2aTrafficEvent({
    headers: request.headers,
    fallbackAgentId: agentId || null,
    action,
    surface: "a2a/integrations",
    entityId: "a2a-integration-catalog",
    reason: agentId ? "external_agent_catalog_discovery" : "catalog_discovery",
    metadata: {
      agent_id: agentId || null,
      integration_count: catalog.integrations.length,
      telegram_roles: catalog.telegram_control_plane.length,
      response_status: 200,
      response_summary: `a2a_integrations_ok:${catalog.integrations.length}`,
    },
  }).catch((error) => {
    console.warn("[a2a/integrations] traffic audit failed", error);
  });

  return NextResponse.json({
    success: true,
    catalog,
    ...(agentId
      ? {
          growth_kit_preview: buildAgentGrowthKit({
            agentId,
            campaign: "a2a-agent-referral",
            source: "integration-catalog",
          }),
        }
      : {}),
  });
}
