import fs from 'fs';
import path from 'path';
import { spawnSync } from 'child_process';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const libraryDir = path.resolve(__dirname, '..', 'dist', 'library');
const outFile = path.resolve(__dirname, '..', 'dfg-3dviewer-library.zip');

if (!fs.existsSync(libraryDir)) {
  console.error('dist/library directory not found. Run `npm run build:library` first.');
  process.exit(1);
}

if (fs.existsSync(outFile)) {
  fs.rmSync(outFile);
}

const zipProcess = spawnSync('zip', ['-rq', outFile, '.'], {
  cwd: libraryDir,
  stdio: 'inherit',
});

if (zipProcess.error) {
  if (zipProcess.error.code === 'ENOENT') {
    console.error('`zip` command not found. Install it before running `npm run pack:library`.');
    process.exit(1);
  }

  throw zipProcess.error;
}

if (zipProcess.status !== 0) {
  process.exit(zipProcess.status ?? 1);
}

const archiveSize = fs.statSync(outFile).size;
console.log(`Created ${outFile} (${archiveSize} total bytes)`);
console.log('Install by extracting to web/libraries/dfg-3dviewer/ on your Drupal site.');
