import { ModuleRegistry } from '../app/kernel/module-registry.mjs';
import { loadBuiltInModules } from '../app/modules/catalog.mjs';

const failures = [];
const assert = (condition, message) => { if (!condition) failures.push(message); };

const modules = loadBuiltInModules();
const registry = new ModuleRegistry();
for (const module of modules) registry.register(module);

let graph = null;
try {
  graph = registry.validateGraph();
} catch (error) {
  failures.push(`${error.code || 'CAPABILITY_GRAPH_INVALID'}: ${error.message}`);
}

const settings = modules.find(item => item.manifest.id === 'vendoo.settings')?.manifest;
const manager = modules.find(item => item.manifest.id === 'vendoo.module-manager')?.manifest;
assert(settings?.provides.includes('settings.configuration'), 'vendoo.settings stellt settings.configuration nicht bereit');
assert(manager?.consumes.includes('settings.configuration'), 'vendoo.module-manager fordert settings.configuration nicht an');
assert(graph?.enabledModules.length === 16, `Erwartet 16 aktivierbare Module, erhalten ${graph?.enabledModules.length ?? 0}`);
assert(graph?.capabilities.includes('settings.configuration'), 'Capability settings.configuration fehlt im aufgelösten Gesamtgraph');
assert(graph?.order.indexOf('vendoo.settings') < graph?.order.indexOf('vendoo.module-manager'), 'vendoo.settings wird nicht vor vendoo.module-manager gestartet');

if (failures.length) {
  console.error(`Capability-Graph-Gate 1.40.2 fehlgeschlagen (${failures.length}):`);
  failures.forEach(item => console.error(`- ${item}`));
  process.exit(1);
}

console.log(`Capability-Graph-Gate 1.40.2 erfolgreich: ${graph.enabledModules.length} Module, ${graph.capabilities.length} Capabilities und vollständige Provider-Verträge geprüft.`);
