import { sanitizeLogLineForApi } from "@/utils/log-line.js";

/** One string per log: `timestamp message` (newest → oldest). */
export function formatDatadogLogLines(
  logs: Array<{ timestamp: string | null; message: string | null }>,
  options?: { hideThinking?: boolean },
): string[] {
  const sorted = [...logs].sort((a, b) => {
    const ta = a.timestamp ? new Date(a.timestamp).getTime() : 0;
    const tb = b.timestamp ? new Date(b.timestamp).getTime() : 0;
    return tb - ta;
  });

  // When hideThinking is active we collect the timestamps of cursor-event
  // entries so we can also drop their split continuation fragments (Datadog
  // breaks very large log lines into multiple entries sharing the same
  // timestamp — the first fragment has the [cursor:*] prefix and gets
  // filtered, but subsequent fragments appear as raw code/JSON snippets
  // without the prefix and would otherwise slip through).
  const filteredTimestamps = new Set<string>();
  if (options?.hideThinking) {
    for (const l of sorted) {
      if (l.timestamp && isThinkingLine(l.message ?? "")) {
        filteredTimestamps.add(l.timestamp);
      }
    }
  }

  const lines: string[] = [];
  for (const l of sorted) {
    if (options?.hideThinking) {
      if (isThinkingLine(l.message ?? "")) continue;
      if (l.timestamp && filteredTimestamps.has(l.timestamp)) continue;
    }
    const msg = sanitizeLogLineForApi(l.message ?? "");
    if (msg.length === 0) continue;
    const ts = l.timestamp ?? "";
    lines.push(`${ts} ${msg}`.trim());
  }
  return lines;
}

/**
 * Returns true when a raw Datadog log message is a verbose cursor agent event
 * (tool call started/completed, prompt, system init, final result, or thinking
 * block). These lines contain the full JSON payload of each agent interaction
 * and are too large and noisy to be useful in the API response.
 */
export function isThinkingLine(raw: string): boolean {
  return (
    raw.includes("[cursor:tool") ||
    raw.includes("[cursor:user") ||
    raw.includes("[cursor:system") ||
    raw.includes("[cursor:result") ||
    raw.includes('"thinkingMessage"')
  );
}
