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;
const deployments = modules.find(item => item.manifest.id === 'vendoo.deployments')?.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 === 17, `Erwartet 17 aktivierbare Module, erhalten ${graph?.enabledModules.length ?? 0}`);
assert(deployments?.consumes.includes('settings.configuration'), 'vendoo.deployments fordert settings.configuration nicht an');
assert(deployments?.consumes.includes('operations.backup'), 'vendoo.deployments fordert operations.backup nicht an');
assert(graph?.capabilities.includes('deployments.coolify'), 'Capability deployments.coolify fehlt im aufgelösten Gesamtgraph');
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');

assert(graph?.order.indexOf('vendoo.module-manager') < graph?.order.indexOf('vendoo.deployments'), 'vendoo.module-manager wird nicht vor vendoo.deployments gestartet');

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

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