#!/usr/bin/env node
/**
 * CI gate — customer bundle paths must not contain forbidden artifacts.
 */
'use strict';

const fs = require('fs');
const path = require('path');
const manifest = require('./packaging-manifest');

const root = path.resolve(__dirname, '..');
let failed = false;

function walk(dir, hits = []) {
  if (!fs.existsSync(dir)) return hits;
  for (const ent of fs.readdirSync(dir, { withFileTypes: true })) {
    const p = path.join(dir, ent.name);
    if (ent.isDirectory()) {
      if (manifest.excludeDirNames.includes(ent.name)) {
        hits.push({ type: 'dir', path: p });
        continue;
      }
      walk(p, hits);
    } else {
      if (manifest.excludeFileNames.includes(ent.name)) hits.push({ type: 'file', path: p });
      if (manifest.excludePatterns.some((re) => re.test(ent.name))) hits.push({ type: 'pattern', path: p });
    }
  }
  return hits;
}

for (const rel of ['releases/_staging', 'src/api/__tests__']) {
  const abs = path.join(root, rel);
  if (fs.existsSync(abs)) {
    console.log(`[verify:packaging] OK excluded path exists in dev only: ${rel}`);
  }
}

const forbiddenInTree = [];
for (const f of ['.env', 'src/web/.env']) {
  const p = path.join(root, f);
  if (fs.existsSync(p)) {
    forbiddenInTree.push(p);
  }
}

if (forbiddenInTree.length) {
  console.warn('[verify:packaging] WARN — live .env present (must be gitignored, never in customer bundle):');
  forbiddenInTree.forEach((p) => console.warn(' ', path.relative(root, p)));
}

const versionRoot = fs.readFileSync(path.join(root, 'VERSION'), 'utf8').trim();
const webPkg = JSON.parse(fs.readFileSync(path.join(root, 'src/web/package.json'), 'utf8'));
if (webPkg.version !== versionRoot) {
  console.error(`[verify:packaging] FAIL — version mismatch VERSION=${versionRoot} web=${webPkg.version}`);
  failed = true;
} else {
  console.log(`[verify:packaging] OK version aligned at ${versionRoot}`);
}

if (failed) process.exit(1);
console.log('[verify:packaging] OK');
