const fs = require('fs');
const path = require('path');
const { spawnSync } = require('child_process');

const root = path.resolve(__dirname, '..');
const packageManagerEntry = process.env.npm_execpath;
const command = packageManagerEntry ? process.execPath : 'pnpm';
const args = packageManagerEntry
  ? [packageManagerEntry, 'exec', 'vite', 'build']
  : ['exec', 'vite', 'build'];

const build = spawnSync(command, args, {
  cwd: root,
  stdio: 'inherit',
});

if (build.error) throw build.error;
if (build.status !== 0) process.exit(build.status ?? 1);

const dist = path.join(root, 'dist');
fs.copyFileSync(
  path.join(root, 'PACK_OPENING_REPLICATION_REPORT.html'),
  path.join(dist, 'PACK_OPENING_REPLICATION_REPORT.html'),
);
for (const file of ['ORIGINAL_PARAMETERS.md', 'REPLICATION_NOTES.md', 'TECH_STACK.md']) {
  fs.copyFileSync(path.join(root, file), path.join(dist, file));
}
fs.cpSync(path.join(root, 'report-assets'), path.join(dist, 'report-assets'), { recursive: true });
const verificationOut = path.join(dist, 'verification');
fs.mkdirSync(verificationOut, { recursive: true });
for (const file of [
  'mobile-carousel.png',
  'mobile-focus.png',
  'mobile-tear.png',
  'mobile-reveal.png',
  'mobile-complete.png',
  'verification.json',
]) {
  fs.copyFileSync(path.join(root, 'verification', file), path.join(verificationOut, file));
}
process.stdout.write('Cloudflare Pages experience bundle prepared in dist/.\n');
