import type { WorkbenchModuleKey, WorkbenchModuleMeta } from './use-workbench-modules';
import type { WorkbenchLayout } from './workbench-layout-types';

/**
 * 把存量布局与当前模块注册中心对齐。
 * - 注册中心存在但布局未含的 key：按 defaultVisible 进 columns 或 hidden
 * - 布局含但注册中心已删除的 key：丢弃
 */
export function reconcileLayout(layout: WorkbenchLayout, modules: WorkbenchModuleMeta[]): WorkbenchLayout {
  const knownKeys = new Set<WorkbenchModuleKey>(modules.map(m => m.key));
  const filterKnown = (list: WorkbenchModuleKey[]) => list.filter(k => knownKeys.has(k));

  const columns = layout.columns.map(c => ({ id: c.id, modules: filterKnown(c.modules) }));
  const hidden = filterKnown(layout.hidden);
  const collapsed = filterKnown(layout.collapsed);

  const appearKeys = new Set<WorkbenchModuleKey>([...columns.flatMap(c => c.modules), ...hidden]);

  for (const m of modules) {
    if (!appearKeys.has(m.key)) {
      if (m.defaultVisible) {
        const target = columns.find(c => c.id === m.defaultColumn) ?? columns[0];
        target.modules.push(m.key);
      } else {
        hidden.push(m.key);
      }
    }
  }

  return { ...layout, columns, hidden, collapsed };
}
