import { buildSessionContextFromPath } from './context_builder.js';
import {
  getPathToLeaf,
  groupChildrenByParent,
  resolveLatestLabels,
} from './path.js';
import { projectSubagentEntries } from './subagent_projection.js';
import type {
  SessionTreeEntry,
  SessionTreeSession,
  SessionTreeSnapshot,
} from './types.js';

export function buildSessionTreeSnapshot(
  session: SessionTreeSession,
  entries: SessionTreeEntry[],
): SessionTreeSnapshot {
  const projectedEntries = projectSubagentEntries(entries);
  const activePath = session.leafEntryId === null
    ? []
    : getPathToLeaf(projectedEntries, session.leafEntryId);

  return {
    session,
    entries: projectedEntries,
    activePath,
    childrenByParentId: groupChildrenByParent(projectedEntries),
    labelsByEntryId: resolveLatestLabels(projectedEntries),
    runtimeContext: buildSessionContextFromPath(activePath),
  };
}
