import { extractStopReason, isTurnBoundary, type StopReason } from "../../lib/stopReason";
import type { CapturedLog } from "../../proxy/schemas";
import { resolveLogFormat } from "./log-formats";

export type TurnEntry = {
  log: CapturedLog;
  stopReason: StopReason;
};

export type TurnGroupData = {
  entries: TurnEntry[];
  turnIndex: number;
};

type ConversationLike = {
  logs: CapturedLog[];
};

export function shouldRenderConversationContent(standalone: boolean, expanded: boolean): boolean {
  return standalone || expanded;
}

export function isTurnCollapsible(
  entryCount: number,
  isComplete: boolean,
  isPending: boolean,
): boolean {
  return entryCount > 1 && isComplete && !isPending;
}

export function buildTurnGroups(logs: CapturedLog[]): TurnGroupData[] {
  const groups: TurnGroupData[] = [];
  let entries: TurnEntry[] = [];
  let turnIndex = 0;

  for (const log of logs) {
    entries.push({ log, stopReason: extractStopReason(log) });
    const current = entries[entries.length - 1];
    if (current !== undefined && isTurnBoundary(current.stopReason)) {
      groups.push({ entries, turnIndex });
      entries = [];
      turnIndex += 1;
    }
  }

  if (entries.length > 0) groups.push({ entries, turnIndex });
  return groups;
}

export function buildValidPredecessors(groups: ConversationLike[]): Map<number, CapturedLog> {
  const predecessors = new Map<number, CapturedLog>();

  for (const group of groups) {
    for (let index = 1; index < group.logs.length; index += 1) {
      const current = group.logs[index];
      const previous = group.logs[index - 1];
      if (current === undefined || previous === undefined) continue;
      const currentFormat = resolveLogFormat(current);
      const previousFormat = resolveLogFormat(previous);
      if (currentFormat === "unknown" || currentFormat !== previousFormat) continue;
      predecessors.set(current.id, previous);
    }
  }

  return predecessors;
}
