import type {
  WizardDirectoriesUiCapability,
  WizardDirectoryContext,
  WizardDirectoryEntry
} from "../types";

export function wizardEntriesForContext(
  capabilities: WizardDirectoriesUiCapability[],
  context: WizardDirectoryContext
): WizardDirectoryEntry[] {
  const entries = capabilities
    .flatMap((capability) => capability.directories)
    .filter((directory) => directory.contextId === context.contextId)
    .sort(
      (left, right) =>
        (left.order ?? 100) - (right.order ?? 100)
        || left.id.localeCompare(right.id)
    )
    .flatMap((directory) => directory.entries(context));

  const unique = new Map<string, WizardDirectoryEntry>();
  for (const entry of entries) {
    const key = `${entry.moduleId}:${entry.id}`;
    if (!unique.has(key)) unique.set(key, entry);
  }
  return [...unique.values()].sort(
    (left, right) =>
      (left.order ?? 100) - (right.order ?? 100)
      || left.label.localeCompare(right.label)
  );
}
