// Responsibility: reclassify a server-terminal debug replay with browser-local transport, decode, and reducer counts.

import type { WorkbenchKafkaDebugReplayResult } from "@/api/workbench-debug";

export interface WorkbenchKafkaDebugClientCounts {
  clientReceived: number;
  decoded: number;
  applied: number;
}

export type WorkbenchKafkaDebugClientFailureCode = "contract_invalid" | "transport_failed" | "decoder_rejected" | "reducer_rejected";

export function classifyWorkbenchKafkaDebugLocalResult(
  serverResult: WorkbenchKafkaDebugReplayResult,
  clientCounts: WorkbenchKafkaDebugClientCounts
): WorkbenchKafkaDebugReplayResult {
  const counts = { ...(serverResult.counts ?? {}), ...clientCounts };
  const overlaid = { ...serverResult, counts, localOverlay: true };
  if (serverResult.code !== "terminal_complete") return overlaid;

  const delivered = nonNegativeInteger(serverResult.counts?.delivered);
  if (delivered === null) {
    return clientFailure(overlaid, "contract_invalid", "服务端 terminal_complete 缺少有效的 delivered 计数。");
  }
  if (clientCounts.clientReceived !== delivered) {
    return clientFailure(overlaid, "transport_failed", `浏览器收到 ${clientCounts.clientReceived} 条，与服务端已投递的 ${delivered} 条不一致。`);
  }
  if (clientCounts.decoded !== clientCounts.clientReceived) {
    return clientFailure(overlaid, "decoder_rejected", `浏览器收到 ${clientCounts.clientReceived} 条，但解码计数为 ${clientCounts.decoded} 条。`);
  }
  if (clientCounts.applied !== clientCounts.decoded) {
    return clientFailure(overlaid, "reducer_rejected", `浏览器解码 ${clientCounts.decoded} 条，但生产 reducer 应用计数为 ${clientCounts.applied} 条。`);
  }
  return { ...overlaid, ok: true, phase: "terminal", code: "terminal_complete" };
}

function clientFailure(result: WorkbenchKafkaDebugReplayResult, code: WorkbenchKafkaDebugClientFailureCode, message: string): WorkbenchKafkaDebugReplayResult {
  return { ...result, ok: false, phase: "client", code, message };
}

function nonNegativeInteger(value: unknown): number | null {
  if (value === null || value === undefined || (typeof value === "string" && value.trim() === "")) return null;
  const parsed = Number(value);
  return Number.isSafeInteger(parsed) && parsed >= 0 ? parsed : null;
}
