import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";

export const dynamic = "force-dynamic";

const MONITOR_TOKEN = process.env.TRAFFIC_MONITOR_TOKEN;

function asRecordJson(value: unknown): Record<string, unknown> | undefined {
  if (typeof value === "object" && value !== null && !Array.isArray(value)) {
    return value as Record<string, unknown>;
  }
  return undefined;
}

function normalizedJudgeResult(value: unknown) {
  if (typeof value !== "string") {
    return "";
  }
  return value.trim().toLowerCase();
}

function normalizeSurface(value: unknown) {
  if (typeof value !== "string") return "unknown";
  const trimmed = value.trim();
  return trimmed.length > 0 ? trimmed : "unknown";
}

function normalizeSourceIp(value: unknown) {
  if (typeof value !== "string") return "unknown";
  const trimmed = value.trim();
  return trimmed.length > 0 ? trimmed : "unknown";
}

function normalizeUserAgent(value: unknown) {
  if (typeof value !== "string") return "unknown";
  const trimmed = value.trim();
  if (!trimmed) return "unknown";

  const lower = trimmed.toLowerCase();
  const tokens = trimmed.split(/[;\s]/).filter((item) => item.length > 0);
  const topToken = tokens[0] || trimmed;

  if (lower.includes("python-requests")) return "python-requests";
  if (lower.includes("curl")) return "curl";
  if (lower.includes("node")) return "node";
  if (lower.includes("openai")) return "openai";
  if (lower.includes("perplexity")) return "perplexity";
  if (lower.includes("anthropic")) return "anthropic";
  if (lower.includes("bot")) return "bot";

  return topToken.length > 48 ? `${topToken.slice(0, 45)}...` : topToken;
}

function normalizePayloadSummary(value: unknown) {
  if (typeof value === "string") {
    const trimmed = value.trim();
    return trimmed.length > 0 ? trimmed : "unknown";
  }

  if (value && typeof value === "object") {
    try {
      return JSON.stringify(value);
    } catch {
      return "unknown";
    }
  }

  return "unknown";
}

const AI_USER_AGENT_HINTS = [
  "gpt",
  "chatgpt",
  "openai",
  "anthropic",
  "claude",
  "perplexity",
  "llm",
  "mcp",
  "autogpt",
  "agent",
  "assistant",
  "gemini",
  "cursor",
  "copilot",
];

type TrafficActorClass = "a2a" | "external_ai_agent" | "likely_ai_agent" | "other_external";

function resolveActorClass(
  action: string,
  actorType: string | null | undefined,
  actorId: string | null | undefined,
  metadata: Record<string, unknown> | undefined,
  surface: string | undefined
) {
  const normalizedSurface = (surface || "").toLowerCase();
  if (normalizedSurface.startsWith("mcp/")) {
    return "a2a";
  }

  const normalizedActorId = (actorId || "").toLowerCase();
  if (actorType === "AGENT" || normalizedActorId.startsWith("agent:")) {
    if (action.startsWith("EXTERNAL_") && normalizedSurface.startsWith("mcp/")) {
      return "a2a";
    }
    return "external_ai_agent";
  }

  if (isLikelyAIAgentActor(actorType, actorId, metadata)) {
    return "likely_ai_agent";
  }

  return "other_external";
}

function resolveMetadata(value: unknown): Record<string, unknown> | undefined {
  if (typeof value === "object" && value !== null && !Array.isArray(value)) {
    return value as Record<string, unknown>;
  }
  return undefined;
}

function resolveDisplayIp(event: { actorType: string | null; actorId: string | null; metadata: unknown }) {
  const metadata = resolveMetadata(event.metadata);
  const metadataIp = typeof metadata?.source_ip === "string" ? metadata.source_ip.trim() : undefined;
  if (metadataIp) {
    return metadataIp;
  }

  if ((event.actorType || "").toUpperCase() === "USER" && event.actorId) {
    const marker = event.actorId.lastIndexOf(":");
    if (marker >= 0) {
      const actorIp = event.actorId.slice(marker + 1).trim();
      if (actorIp) {
        return actorIp;
      }
    }
  }

  if ((event.actorType || "").toUpperCase() === "SYSTEM") {
    return "system";
  }

  return "unknown";
}

function resolveDisplayUserAgent(event: { actorType: string | null; metadata: unknown }) {
  const metadata = resolveMetadata(event.metadata);
  const metadataUa =
    typeof metadata?.user_agent === "string"
      ? metadata.user_agent
      : typeof metadata?.userAgent === "string"
      ? metadata.userAgent
      : undefined;

  if (!metadataUa && (event.actorType || "").toUpperCase() === "SYSTEM") {
    return "system";
  }

  return normalizeUserAgent(metadataUa);
}

function resolveResponseStatus(event: { metadata: unknown }) {
  const metadata = resolveMetadata(event.metadata);
  const value = metadata?.response_status;

  if (typeof value === "number") {
    return value;
  }

  if (typeof value === "string") {
    const parsed = Number.parseInt(value, 10);
    if (Number.isFinite(parsed)) {
      return parsed;
    }
  }

  return undefined;
}

function isLikelyAIAgentActor(
  actorType: string | null | undefined,
  actorId: string | null | undefined,
  metadata: Record<string, unknown> | undefined
) {
  if (actorType === "AGENT") {
    return true;
  }

  const normalizedActor = (actorId || "").toLowerCase();
  if (normalizedActor.startsWith("agent:")) {
    return true;
  }

  const userAgent = String(metadata?.user_agent || "").toLowerCase();
  if (AI_USER_AGENT_HINTS.some((token) => userAgent.includes(token))) {
    return true;
  }

  const requestHeaders = asRecordJson(metadata?.request_actor_headers);
  if (!requestHeaders) {
    return false;
  }

  const headerText = Object.values(requestHeaders)
    .filter((item): item is string => typeof item === "string")
    .join(" ")
    .toLowerCase();

  return AI_USER_AGENT_HINTS.some((token) => headerText.includes(token));
}

function classifyActorSource(
  actorType: string | null | undefined,
  actorId: string | null | undefined,
  metadata: Record<string, unknown> | undefined
) {
  if (actorType === "AGENT" || (actorId || "").toLowerCase().startsWith("agent:")) {
    return "AGENT";
  }
  if (isLikelyAIAgentActor(actorType, actorId, metadata)) {
    return "LIKELY_AI";
  }
  return "OTHER";
}

function addCountedBucket(store: Map<string, { events: number; actors: Set<string>; latestAt: number }>, key: string, actorId: string, eventAt: number) {
  const bucket = store.get(key);
  if (!bucket) {
    store.set(key, { events: 1, actors: new Set([actorId]), latestAt: eventAt });
    return;
  }

  bucket.events += 1;
  bucket.actors.add(actorId);
  if (eventAt > bucket.latestAt) {
    bucket.latestAt = eventAt;
  }
}

type ActorSourceBucket = {
  events: number;
  actors: Set<string>;
  latestAt: number;
  surface?: string;
  sourceIp?: string;
  userAgent?: string;
};

const updateActorBucket = (
  store: Map<string, ActorSourceBucket>,
  key: string,
  actorId: string,
  eventAt: number,
  keyField: Record<string, string>
) => {
  const bucket = store.get(key);
  if (!bucket) {
    store.set(key, {
      ...keyField,
      events: 1,
      actors: new Set([actorId]),
      latestAt: eventAt,
    });
    return;
  }

  bucket.events += 1;
  bucket.actors.add(actorId);
  if (eventAt > bucket.latestAt) {
    bucket.latestAt = eventAt;
  }
};

function isMissingTableError(error: unknown): boolean {
  return (
    typeof error === "object" &&
    error !== null &&
    "code" in error &&
    (error as { code: string }).code === "P2021"
  );
}

export async function GET(request: NextRequest) {
  if (!MONITOR_TOKEN && process.env.NODE_ENV === "production") {
    console.error("[traffic] TRAFFIC_MONITOR_TOKEN must be configured in production.");
    return NextResponse.json({ error: "Traffic monitor token is not configured" }, { status: 503 });
  }

  if (MONITOR_TOKEN) {
    const queryToken = request.nextUrl.searchParams.get("token");
    const token = request.headers.get("x-traffic-token") || queryToken;
    if (token !== MONITOR_TOKEN) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }
  }

  const query = request.nextUrl.searchParams;
  const minutes = Math.max(parseInt(query.get("minutes") || "1440", 10), 5);
  const since = new Date(Date.now() - minutes * 60 * 1000);

  const [
    summaryRows,
    actorSummaryRows,
    externalActorRows,
    totalRows,
    latestEvents,
    judgeCompleteRows,
    demandPoolCount,
    demandPoolNewRows,
    demandPoolScopeStats,
  ] = await Promise.all([
    prisma.auditEvent.groupBy({
      by: ["action"],
      where: {
        createdAt: { gte: since },
      },
      _count: { _all: true },
    }),
    prisma.auditEvent.groupBy({
      by: ["actorType"],
      where: {
        createdAt: { gte: since },
      },
      _count: { _all: true },
    }),
    prisma.auditEvent.groupBy({
      by: ["actorId"],
      where: {
        createdAt: { gte: since },
        action: {
          startsWith: "EXTERNAL_",
        },
      },
      _count: { _all: true },
    }),
    prisma.auditEvent.count({
      where: { createdAt: { gte: since } },
    }),
    prisma.auditEvent.findMany({
      where: {
        createdAt: { gte: since },
      },
      orderBy: {
        createdAt: "desc",
      },
      take: 120,
      select: {
        id: true,
        action: true,
        actorType: true,
        actorId: true,
        entityType: true,
        entityId: true,
        reason: true,
        metadata: true,
        createdAt: true,
      },
    }),
    prisma.auditEvent.findMany({
      where: {
        createdAt: { gte: since },
        action: "JUDGE_COMPLETE",
      },
      select: {
        metadata: true,
      },
    }),
    prisma.task.count({
      where: {
        status: "OPEN",
        title: {
          not: {
            startsWith: "GitHub Issue:",
          },
        },
      },
    }),
    prisma.task.count({
      where: {
        status: "OPEN",
        title: {
          not: {
            startsWith: "GitHub Issue:",
          },
        },
        created_at: { gte: since },
      },
    }),
    prisma.task.aggregate({
      where: {
        status: "OPEN",
        title: {
          not: {
            startsWith: "GitHub Issue:",
          },
        },
      },
      _avg: {
        scope_clarity_score: true,
      },
    }),
  ]);

  const demandSupply = {
    open_task_count: demandPoolCount,
    new_open_tasks_in_window: demandPoolNewRows,
    avg_scope_clarity: demandPoolScopeStats._avg.scope_clarity_score,
  };

  let capturedPayoutCount = 0;
  let releasedPayoutCount = 0;
  try {
    [capturedPayoutCount, releasedPayoutCount] = await Promise.all([
      prisma.ledgerEntry.count({
        where: {
          created_at: { gte: since },
          phase: "CAPTURE",
          response_status: "SUCCESS",
        },
      }),
      prisma.ledgerEntry.count({
        where: {
          created_at: { gte: since },
          phase: "RELEASE",
          response_status: "SUCCESS",
        },
      }),
    ]);
  } catch (error) {
    if (!isMissingTableError(error)) {
      throw error;
    }
  }

  const actionSummary = Object.fromEntries(
    summaryRows.map((row) => [row.action, row._count._all])
  );

  const actorSummary = Object.fromEntries(
    actorSummaryRows.map((row) => [row.actorType, row._count._all])
  );

  const isInternalActorId = (actorId: string | null | undefined) => {
    if (!actorId) return true;
    const normalized = actorId.toLowerCase();

    if (normalized === "unknown" || normalized === "mcp-anonymous") {
      return true;
    }

    const ipMatch = normalized.match(/^open-tasks:([a-z0-9.:_-]+)$/);
    if (!ipMatch?.[1]) {
      return false;
    }

    const actorIp = ipMatch[1];
    if (actorIp.startsWith("127.") || actorIp.startsWith("10.") || actorIp.startsWith("192.168.")) {
      return true;
    }

    if (actorIp.startsWith("172.")) {
      const secondOctet = Number(actorIp.split(".")[1]);
      return secondOctet >= 16 && secondOctet <= 31;
    }

    if (actorIp === "localhost" || actorIp === "unknown" || actorIp.startsWith("fc") || actorIp.startsWith("fd")) {
      return true;
    }

    return false;
  };

  const isInternalActor = (params: {
    actorType: string | null | undefined;
    actorId: string | null | undefined;
  }) => {
    if (params.actorType === "AGENT") return false;
    return isInternalActorId(params.actorId);
  };

  const externalActorSummary = externalActorRows
    .map((row) => ({
      actorId: row.actorId || "unknown",
      events: row._count._all,
    }))
    .filter((row) => !isInternalActorId(row.actorId))
    .sort((a, b) => b.events - a.events)
    .slice(0, 20);

  const channelSummary = Object.entries(actionSummary).reduce(
    (acc, [action, count]) => {
      if (action.startsWith("EXTERNAL_")) {
        acc.external += count;
      } else {
        acc.internal += count;
      }
      return acc;
    },
    { external: 0, internal: 0 } as Record<string, number>
  );

  const discoveryEvents =
    (actionSummary["EXTERNAL_LIST_OPEN_TASKS"] || 0) +
    (actionSummary["EXTERNAL_LIST_OPEN_TASKS_MCP"] || 0) +
    (actionSummary["EXTERNAL_A2A_INTEGRATION_CATALOG_VIEW"] || 0) +
    (actionSummary["EXTERNAL_A2A_GROWTH_KIT_ISSUED"] || 0);

  const proposalViewEvents = actionSummary["EXTERNAL_DEMAND_PROPOSAL_VIEW"] || 0;
  const proposalCreatedEvents = actionSummary["EXTERNAL_DEMAND_PROPOSAL_INTAKE_CREATED"] || 0;
  const proposalCheckoutEvents = actionSummary["EXTERNAL_DEMAND_PROPOSAL_CHECKOUT_STARTED"] || 0;
  const proposalWalletPendingEvents = actionSummary["EXTERNAL_DEMAND_PROPOSAL_WALLET_PAYMENT_PENDING"] || 0;
  const proposalPaidEvents = actionSummary["EXTERNAL_DEMAND_PROPOSAL_FEE_CAPTURED"] || 0;
  const claimEvents = actionSummary["EXTERNAL_CLAIM_TASK_SUCCESS"] || 0;
  const submitEvents = actionSummary["EXTERNAL_SUBMIT_SOLUTION_SUCCESS"] || 0;
  const judgePassEvents = judgeCompleteRows.filter((row) => {
    const metadata = asRecordJson(row.metadata);
    return normalizedJudgeResult(metadata?.overall_result) === "pass";
  }).length;
  const judgeFailEvents = judgeCompleteRows.filter((row) => {
    const metadata = asRecordJson(row.metadata);
    return normalizedJudgeResult(metadata?.overall_result) === "fail";
  }).length;

  const conversionRate = (numerator: number, denominator: number) => {
    if (!denominator) return 0;
    return Math.round((numerator / denominator) * 1000) / 10;
  };

  const externalFunnel = {
    discovery_events: discoveryEvents,
    proposal_view_events: proposalViewEvents,
    proposal_created_events: proposalCreatedEvents,
    proposal_checkout_events: proposalCheckoutEvents,
    proposal_wallet_pending_events: proposalWalletPendingEvents,
    proposal_paid_events: proposalPaidEvents,
    claim_events: claimEvents,
    submit_events: submitEvents,
    judge_pass_events: judgePassEvents,
    judge_fail_events: judgeFailEvents,
    judge_total_events: judgePassEvents + judgeFailEvents,
    payout_captured: capturedPayoutCount,
    payout_released: releasedPayoutCount,
  };

  const conversionRates = {
    proposal_view_rate: conversionRate(proposalViewEvents, discoveryEvents),
    proposal_create_rate: conversionRate(proposalCreatedEvents, proposalViewEvents),
    proposal_paid_rate: conversionRate(proposalPaidEvents, proposalCreatedEvents),
    claim_rate: conversionRate(claimEvents, discoveryEvents),
    submit_rate: conversionRate(submitEvents, claimEvents),
    pass_rate: conversionRate(judgePassEvents, submitEvents),
    payout_rate: conversionRate(capturedPayoutCount, judgePassEvents),
  };

  const externalEventTypes = Object.entries(actionSummary)
    .filter(([action]) => action.startsWith("EXTERNAL_"))
    .map(([action, count]) => ({ action, count }));

  const internalEventTypes = Object.entries(actionSummary)
    .filter(([action]) => !action.startsWith("EXTERNAL_"))
    .map(([action, count]) => ({ action, count }));

  const recentEvents = latestEvents.map((event) => {
    const metadata = asRecordJson(event.metadata);
    const actorClass =
      event.action.startsWith("EXTERNAL_") && !isInternalActor({ actorType: event.actorType, actorId: event.actorId })
        ? resolveActorClass(
            event.action,
            event.actorType,
            event.actorId,
            metadata,
            typeof metadata?.surface === "string" ? metadata.surface : undefined
          )
        : "other_external";

    return {
      id: event.id,
      action: event.action,
      actorType: event.actorType,
      actorId: event.actorId,
      entityType: event.entityType,
      entityId: event.entityId,
      reason: event.reason,
      createdAt: event.createdAt,
      surface: metadata?.surface,
      level: metadata?.level,
      actorSource: classifyActorSource(event.actorType, event.actorId, metadata),
      actorClass,
      metadata,
    };
  });

  const externalSourceSurfaceMap = new Map<string, { surface: string; events: number; actors: Set<string>; latestAt: number }>();
  const externalIpSurfaceMap = new Map<string, { sourceIp: string; events: number; actors: Set<string>; latestAt: number }>();
  const externalUserAgentMap = new Map<string, { userAgent: string; events: number; actors: Set<string>; latestAt: number }>();
  const responseStatusSummary = new Map<string, { responseStatus: string; events: number; actors: Set<string>; latestAt: number }>();
  const externalErrorRows: Array<{
    actor_id: string;
    actor_type: string;
    action: string;
    task_id: string;
    surface: string;
    source_ip: string;
    user_agent: string;
    response_status: number | null;
    error_name: string;
    error_message: string;
    created_at_ms: number;
  }> = [];
  const externalActorActivities: Map<string, {
    actor_id: string;
    events: number;
    actor_class: TrafficActorClass;
    latest_action: string;
    latest_surface: string;
    latest_source_ip: string;
    latest_user_agent: string;
    latest_task_id: string;
    latest_response_status: number | null;
    latest_response_summary: string;
    latest_reason: string;
    latest_payload_summary: string;
    latest_request_id: string;
    latest_created_at_ms: number;
  }> = new Map();
  const externalActorClassSummary = new Map<TrafficActorClass, { events: number; actors: Set<string> }>();

  recentEvents.forEach((event) => {
    const actorId = event.actorId || "agent:unknown";
    const metadata = asRecordJson(event.metadata);
    const actorClass = resolveActorClass(
      event.action,
      event.actorType,
      event.actorId,
      metadata,
      typeof event.surface === "string" ? event.surface : undefined
    );
    if (event.action.startsWith("EXTERNAL_")) {
      const bucket = externalActorClassSummary.get(actorClass);
      if (!bucket) {
        externalActorClassSummary.set(actorClass, { events: 1, actors: new Set([actorId]) });
      } else {
        bucket.events += 1;
        bucket.actors.add(actorId);
      }
    }
    const normalizedSurface = normalizeSurface(event.surface);
    const normalizedIp = normalizeSourceIp(metadata?.source_ip);
    const normalizedUa = normalizeUserAgent(metadata?.user_agent);
    const isTrackedExternalActor =
      event.action.startsWith("EXTERNAL_") &&
      !isInternalActor({ actorType: event.actorType, actorId: event.actorId }) &&
      (actorClass === "a2a" || actorClass === "external_ai_agent" || actorClass === "likely_ai_agent");

    if (!isTrackedExternalActor) {
      return;
    }

    const eventAt = event.createdAt.getTime();
    const responseStatus =
      typeof metadata?.response_status === "number"
        ? metadata.response_status
        : typeof metadata?.response_status === "string"
        ? Number.parseInt(metadata.response_status, 10)
        : null;

    const fallbackErrorName =
      event.action === "EXTERNAL_MCP_AUTH_MISSING"
        ? "AUTH_MISSING"
        : event.action === "EXTERNAL_MCP_AUTH_FORBIDDEN"
        ? "AUTH_FORBIDDEN"
        : event.action.includes("FAIL")
        ? "INTERNAL_ERROR"
        : ""
;

    const fallbackErrorMessage =
      typeof metadata?.auth_issue === "string"
        ? metadata.auth_issue
        : typeof event.reason === "string"
        ? event.reason
        : typeof metadata?.response_summary === "string"
        ? metadata.response_summary
        : ""
;

    const errorName =
      typeof metadata?.error_name === "string" && metadata.error_name.length > 0
        ? metadata.error_name
        : fallbackErrorName;
    const errorMessage =
      typeof metadata?.error_message === "string" && metadata.error_message.length > 0
        ? metadata.error_message
        : fallbackErrorMessage;
    const taskId = typeof metadata?.task_id === "string" ? metadata.task_id : (event.entityId || "-");
    const responseSummary =
      typeof metadata?.response_summary === "string" ? metadata.response_summary : "unknown";

    updateActorBucket(externalSourceSurfaceMap, normalizedSurface, actorId, eventAt, { surface: normalizedSurface });
    updateActorBucket(externalIpSurfaceMap, normalizedIp, actorId, eventAt, { sourceIp: normalizedIp });
    updateActorBucket(externalUserAgentMap, normalizedUa, actorId, eventAt, { userAgent: normalizedUa });
    addCountedBucket(responseStatusSummary, String(responseStatus ?? "n/a"), actorId, eventAt);

    const existingActorActivity = externalActorActivities.get(actorId);
    if (!existingActorActivity) {
      externalActorActivities.set(actorId, {
        actor_id: actorId,
        events: 1,
        actor_class: actorClass,
        latest_action: event.action,
        latest_surface: normalizedSurface,
        latest_source_ip: normalizedIp,
        latest_user_agent: normalizedUa,
        latest_task_id: taskId,
        latest_response_status: responseStatus,
        latest_response_summary: responseSummary,
        latest_reason: event.reason || "unknown",
        latest_payload_summary:
          normalizePayloadSummary(metadata?.payload_summary),
        latest_request_id:
          typeof metadata?.request_id === "string" ? metadata.request_id : "unknown",
        latest_created_at_ms: eventAt,
      });
    } else {
      existingActorActivity.events += 1;

      if (eventAt > existingActorActivity.latest_created_at_ms) {
        existingActorActivity.latest_action = event.action;
        existingActorActivity.latest_surface = normalizedSurface;
        existingActorActivity.latest_source_ip = normalizedIp;
        existingActorActivity.latest_user_agent = normalizedUa;
        existingActorActivity.latest_task_id = taskId;
        existingActorActivity.latest_response_status = responseStatus;
        existingActorActivity.latest_response_summary = responseSummary;
        existingActorActivity.latest_reason = event.reason || "unknown";
        existingActorActivity.latest_payload_summary =
          normalizePayloadSummary(metadata?.payload_summary);
        existingActorActivity.latest_request_id =
          typeof metadata?.request_id === "string" ? metadata.request_id : "unknown";
        existingActorActivity.latest_created_at_ms = eventAt;
      }
    }

    if (
      event.action.includes("ERROR") ||
      event.action.includes("FORBIDDEN") ||
      event.action.includes("MISSING")
    ) {
      externalErrorRows.push({
        actor_id: actorId,
        actor_type: event.actorType || "USER",
        action: event.action,
        task_id: taskId,
        surface: normalizedSurface,
        source_ip: normalizedIp,
        user_agent: normalizedUa,
        response_status: responseStatus,
        error_name: errorName || "unknown",
        error_message: errorMessage || "unknown",
        created_at_ms: eventAt,
      });
    }
  });

  const recentExternalEvents = recentEvents
    .filter(
      (event) =>
        event.action.startsWith("EXTERNAL_") &&
        !isInternalActor({
          actorType: event.actorType,
          actorId: event.actorId,
        })
    )
    .map((event) => ({
      ...event,
      source_ip: resolveDisplayIp(event),
      user_agent: resolveDisplayUserAgent(event),
      response_status: resolveResponseStatus(event),
    }));

  const recentInternalEvents = recentEvents
    .filter((event) => !event.action.startsWith("EXTERNAL_"))
    .map((event) => ({
      ...event,
      source_ip: resolveDisplayIp(event),
      user_agent: resolveDisplayUserAgent(event),
      response_status: resolveResponseStatus(event),
    }));

  const externalSurfaceSummary = Array.from(externalSourceSurfaceMap.entries())
    .map(([surface, bucket]) => ({
      surface,
      events: bucket.events,
      actors: bucket.actors.size,
      latest_at: bucket.latestAt,
    }))
    .sort((a, b) => b.events - a.events);

  const externalSourceIpSummary = Array.from(externalIpSurfaceMap.entries())
    .map(([sourceIp, bucket]) => ({
      source_ip: sourceIp,
      events: bucket.events,
      actors: bucket.actors.size,
      latest_at: bucket.latestAt,
    }))
    .sort((a, b) => b.events - a.events);

  const externalUserAgentSummary = Array.from(externalUserAgentMap.entries())
    .map(([userAgent, bucket]) => ({
      user_agent: userAgent,
      events: bucket.events,
      actors: bucket.actors.size,
      latest_at: bucket.latestAt,
    }))
    .sort((a, b) => b.events - a.events);

  const externalResponseStatusSummary = Array.from(responseStatusSummary.entries())
    .map(([responseStatus, bucket]) => ({
      response_status: responseStatus,
      events: bucket.events,
      actors: bucket.actors.size,
      latest_at: bucket.latestAt,
    }))
    .sort((a, b) => b.events - a.events);

  const externalErrorRowsSorted = externalErrorRows
    .sort((left, right) => right.created_at_ms - left.created_at_ms)
    .slice(0, 30);

  const externalActorActivityRows = Array.from(externalActorActivities.values())
    .sort((left, right) => {
      if (right.events !== left.events) {
        return right.events - left.events;
      }
      return right.latest_created_at_ms - left.latest_created_at_ms;
    })
    .slice(0, 40);

  const externalActorClassSummaryRows = Array.from(externalActorClassSummary.entries())
    .map(([actorClass, bucket]) => ({
      actor_class: actorClass,
      events: bucket.events,
      actors: bucket.actors.size,
    }))
    .sort((a, b) => b.events - a.events);

  return NextResponse.json({
    period_minutes: minutes,
    total_events: totalRows,
    action_summary: actionSummary,
    demand_supply: demandSupply,
    channel_summary: channelSummary,
    actor_summary: actorSummary,
    external_actor_summary: externalActorSummary,
    external_funnel: externalFunnel,
    conversion_rates: conversionRates,
    external_event_types: externalEventTypes,
    internal_event_types: internalEventTypes,
    external_surface_summary: externalSurfaceSummary,
    external_source_ip_summary: externalSourceIpSummary,
    external_user_agent_summary: externalUserAgentSummary,
    external_response_status_summary: externalResponseStatusSummary,
    external_actor_class_summary: externalActorClassSummaryRows,
    external_actor_activities: externalActorActivityRows,
    external_error_rows: externalErrorRowsSorted,
    recent_external_events: recentExternalEvents,
    recent_internal_events: recentInternalEvents,
    updated_at: new Date().toISOString(),
  });
}
