import { mkdtempSync } from 'node:fs';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import { closeVendooDatabase, removeTempDirectory } from './test-runtime-cleanup.mjs';

const tempPrefix = process.env.VENDOO_TEST_TEMP_PREFIX || 'vendoo-capability-graph-';
const temp = mkdtempSync(join(tmpdir(), tempPrefix));
process.env.NODE_ENV = 'test';
process.env.VENDOO_DATA_DIR = temp;
process.env.VENDOO_DB_PATH = join(temp, 'db', 'vendoo.db');
process.env.VENDOO_CONFIG_PATH = join(temp, 'config', 'vendoo.env');
process.env.VENDOO_MODULE_STATE_PATH = join(temp, 'config', 'modules-state.json');
process.env.VENDOO_MODULES_DIR = join(temp, 'modules');

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

try {
  const { ModuleRegistry } = await import('../app/kernel/module-registry.mjs');
  const { loadBuiltInModules } = await import('../app/modules/catalog.mjs');
  const modules = loadBuiltInModules();
  const registry = new ModuleRegistry();
  for (const module of modules) registry.register(module);

  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 === 18, `Erwartet 18 registrierte 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?.capabilities.includes('product-images.variants'), 'Capability product-images.variants 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');
} finally {
  await closeVendooDatabase({ failures, label: 'Capability-Graph-Testdatenbank' });
  await removeTempDirectory(temp, { failures, label: 'Capability-Graph-Testordner' });
}

if (failures.length) {
  console.error(`Capability-Graph-Gate 1.41.2 fehlgeschlagen (${failures.length}):`);
  failures.forEach(item => console.error(`- ${item}`));
  process.exit(1);
}
console.log(`Capability-Graph-Gate 1.41.2 erfolgreich: ${graph.enabledModules.length} Module, ${graph.capabilities.length} Capabilities und vollständige Provider-Verträge geprüft.`);
