#!/usr/bin/env node
/**
 * Customer bundle + SHA256 checksum manifest for release integrity.
 * Output: dist/DBAOps-Sovereign-<version>-enterprise/
 */
const crypto = require('crypto');
const fs = require('fs');
const path = require('path');
const manifest = require('./packaging-manifest');

const root = path.resolve(__dirname, '..');
const version = fs.readFileSync(path.join(root, manifest.versionFile), 'utf8').trim();
const outName = `DBAOps-Sovereign-${version}-enterprise`;
const out = path.join(root, 'dist', outName);

function rmrf(p) {
  if (fs.existsSync(p)) fs.rmSync(p, { recursive: true, force: true });
}

function shouldSkip(name, isDir) {
  if (manifest.excludeDirNames.includes(name)) return true;
  if (!isDir && manifest.excludeFileNames.includes(name)) return true;
  if (!isDir && manifest.excludePatterns.some((re) => re.test(name))) return true;
  return false;
}

function copyDirFiltered(src, dest) {
  if (!fs.existsSync(src)) return;
  fs.mkdirSync(dest, { recursive: true });
  for (const ent of fs.readdirSync(src, { withFileTypes: true })) {
    if (shouldSkip(ent.name, ent.isDirectory())) continue;
    const s = path.join(src, ent.name);
    const d = path.join(dest, ent.name);
    if (ent.isDirectory()) copyDirFiltered(s, d);
    else fs.copyFileSync(s, d);
  }
}

function sha256File(filePath) {
  const hash = crypto.createHash('sha256');
  hash.update(fs.readFileSync(filePath));
  return hash.digest('hex');
}

function walkHashes(dir, base = dir, rows = []) {
  for (const ent of fs.readdirSync(dir, { withFileTypes: true })) {
    const p = path.join(dir, ent.name);
    if (ent.isDirectory()) walkHashes(p, base, rows);
    else {
      const rel = path.relative(base, p).replace(/\\/g, '/');
      rows.push({ path: rel, sha256: sha256File(p), bytes: fs.statSync(p).size });
    }
  }
  return rows;
}

rmrf(out);
fs.mkdirSync(out, { recursive: true });

for (const f of manifest.includeTopLevel) {
  const p = path.join(root, f);
  if (fs.existsSync(p)) fs.copyFileSync(p, path.join(out, f));
}

for (const dir of manifest.includeDirs) {
  copyDirFiltered(path.join(root, dir), path.join(out, dir));
}

fs.copyFileSync(path.join(__dirname, 'packaging-manifest.js'), path.join(out, 'scripts/packaging-manifest.js'));

const readme = `DBAOps Sovereign - Enterprise release bundle
Version: ${version}
Vendor: RHOYLLE INNOVATION EMPIRE LLC

Install: docs/ENTERPRISE-INSTALL.md
Security: docs/SECURITY-PERMISSIONS.md
Uninstall: docs/UNINSTALL.md
Cold deploy proof: scripts/deploy-cold.ps1

Verify integrity: compare CHECKSUMS-SHA256.json against shipped files.
`;
fs.writeFileSync(path.join(out, 'READ-ME-FIRST.txt'), readme, 'utf8');

const checksums = walkHashes(out).sort((a, b) => a.path.localeCompare(b.path));
const checksumDoc = {
  product: 'DBAOps-Sovereign',
  version,
  generatedAt: new Date().toISOString(),
  algorithm: 'SHA256',
  files: checksums,
};
fs.writeFileSync(path.join(out, 'CHECKSUMS-SHA256.json'), JSON.stringify(checksumDoc, null, 2), 'utf8');

console.log('Enterprise bundle:', out);
console.log('Version:', version);
console.log('Files:', checksums.length);
console.log('Checksum manifest:', path.join(out, 'CHECKSUMS-SHA256.json'));
