import { sanitizePublicText } from "./public-sanitizer.js";

export function projectThreadGroups(threads = [], sessions = [], sanitizerConfig = {}) {
  const groupByThread = new Map();
  for (const session of sessions) {
    for (const ref of session.threadRefs ?? []) {
      groupByThread.set(threadKey(ref.accountId, ref.threadId), session);
    }
  }

  const emitted = new Set();
  const rows = [];
  for (const thread of threads) {
    const session = groupByThread.get(threadKey(thread.ownerId, thread.id));
    if (!session) {
      rows.push(thread);
      continue;
    }
    if (emitted.has(session.id)) continue;
    emitted.add(session.id);
    const current = threads.find((item) => item.ownerId === session.accountId && item.id === session.codexThreadId) ?? thread;
    rows.push({
      ...current,
      id: session.codexThreadId,
      ownerId: session.accountId,
      ...(session.conversationTitle ? { preview: sanitizePublicText(session.conversationTitle, sanitizerConfig) } : {}),
      linkedSessionId: session.id
    });
  }
  return rows;
}

function threadKey(accountId, threadId) {
  return `${accountId}:${threadId}`;
}
