import { readFileSync } from 'node:fs';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { ModuleRegistry } from '../app/kernel/module-registry.mjs';
import { PolicyEngine } from '../app/kernel/policy-engine.mjs';
import { RouteRegistry } from '../app/kernel/route-registry.mjs';
import { loadBuiltInModules } from '../app/modules/catalog.mjs';
const root=resolve(dirname(fileURLToPath(import.meta.url)),'..');const failures=[];const assert=(c,m)=>{if(!c)failures.push(m)};const expectThrow=async(fn,code,msg)=>{try{await fn();failures.push(msg)}catch(e){if(e.code!==code)failures.push(`${msg} (${e.code||e.message})`)}};
const pkg=JSON.parse(readFileSync(join(root,'package.json'),'utf8'));assert(pkg.version==='1.39.0',`package.json ist ${pkg.version}`);
const modules=loadBuiltInModules();assert(modules.length===15,`Erwartet 15 Module, erhalten ${modules.length}`);const nativeIds=modules.filter(x=>x.manifest.status==='native').map(x=>x.manifest.id).sort();for(const id of ['vendoo.auth','vendoo.inventory','vendoo.listings','vendoo.media','vendoo.security','vendoo.sessions','vendoo.settings','vendoo.themes','vendoo.users'])assert(nativeIds.includes(id),`Natives Modul fehlt: ${id}`);assert(nativeIds.length===9,`Erwartet 9 native Module, erhalten ${nativeIds.length}`);assert(modules.filter(x=>x.manifest.status==='legacy-bridge').length===6,'Es müssen 6 Legacy-Bridges verbleiben');
const registry=new ModuleRegistry();for(const module of modules)registry.register(module);assert(registry.snapshot().length===15,'Modulregistrierung unvollständig');
const cycle=new ModuleRegistry();cycle.register({manifest:{schemaVersion:1,id:'vendoo.a',name:'A',version:'1.0.0',type:'feature',status:'native',requires:['vendoo.b'],permissions:[],provides:['a.ready'],consumes:[],owns:['a.state']}});cycle.register({manifest:{schemaVersion:1,id:'vendoo.b',name:'B',version:'1.0.0',type:'feature',status:'native',requires:['vendoo.a'],permissions:[],provides:['b.ready'],consumes:[],owns:['b.state']}});await expectThrow(()=>cycle.startAll({}),'MODULE_DEPENDENCY_CYCLE','Zyklus wurde nicht blockiert');
const policies=new PolicyEngine();policies.register('listings.view',({user})=>Boolean(user));const routes=new RouteRegistry({policyEngine:policies});const fake={get(_p,h){this.handler=h}};await expectThrow(()=>routes.register(fake,{id:'listings.no-policy',method:'GET',path:'/x',owner:'vendoo.listings',handler(){}}),'ROUTE_POLICY_REQUIRED','Route ohne Policy wurde akzeptiert');routes.register(fake,{id:'listings.catalog.read-test',method:'GET',path:'/x',owner:'vendoo.listings',policy:'listings.view',csrf:false,handler(_q,r){r.json({ok:true})}});let status=0;await fake.handler({user:null,requestId:'test'},{headersSent:false,status(c){status=c;return this},json(){}},()=>{});assert(status===403,`Deny-by-default ergab ${status}`);
const kernel=readFileSync(join(root,'app/kernel/platform-kernel.mjs'),'utf8');for(const marker of ["policies.register('listings.view'","policies.register('inventory.manage'","policies.register('media.delete'","features.define('catalog.native-listings'","features.define('catalog.native-media'"])assert(kernel.includes(marker),`Kernelvertrag fehlt: ${marker}`);
if(failures.length){console.error(`Platform-Architecture-Gate 1.39.0 fehlgeschlagen (${failures.length}):`);failures.forEach(x=>console.error(`- ${x}`));process.exit(1)}console.log('Platform-Architecture-Gate 1.39.0 erfolgreich: 15 Module, 9 native Module, 6 Legacy-Bridges sowie Listings-/Inventory-/Media-Policies geprüft.');
