const ACTIVE_SESSION_STATUSES = new Set(["sending", "starting", "thinking", "running", "waiting_approval", "waiting_response"]);

export function activeSessions(sessions = [], currentSession) {
  const byId = new Map(sessions.map((session) => [session.id, session]));
  if (currentSession?.id) byId.set(currentSession.id, currentSession);
  return [...byId.values()]
    .filter((session) => ACTIVE_SESSION_STATUSES.has(session.status))
    .sort((left, right) => new Date(right.updatedAt).getTime() - new Date(left.updatedAt).getTime());
}

export function otherActiveSessions(sessions = [], currentSession) {
  return activeSessions(sessions, currentSession).filter((session) => session.id !== currentSession?.id);
}

export function activeSessionTitle(session, threads = [], fallback, capturedTitle) {
  if (session.conversationTitle?.trim()) return session.conversationTitle.trim();
  if (capturedTitle?.trim()) return capturedTitle.trim();
  const thread = threads.find((item) => item.ownerId === session.accountId && item.id === session.codexThreadId);
  return thread?.name?.trim() || thread?.preview?.trim() || fallback;
}
