import { mkdir, mkdtemp, rm, cp, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { execFile } from 'node:child_process';
import { promisify } from 'node:util';

const execFileAsync = promisify(execFile);
const packageName = 'opencascade.js@1.1.1';
const scratch = await mkdtemp(join(tmpdir(), 'polymodel-ocjs-'));

try {
  const { stdout } = await execFileAsync('npm', ['pack', packageName, '--silent'], { cwd: scratch });
  const tarball = stdout.trim().split('\n').at(-1);
  const packageDir = join(scratch, 'package');
  await mkdir(packageDir);
  await execFileAsync('tar', ['-xzf', tarball, '-C', packageDir, '--strip-components=1'], { cwd: scratch });

  const outDir = join(process.cwd(), 'public/vendor/opencascade');
  await rm(outDir, { recursive: true, force: true });
  await mkdir(outDir, { recursive: true });
  await cp(join(packageDir, 'dist/opencascade.wasm.js'), join(outDir, 'opencascade.js'));
  await cp(join(packageDir, 'dist/opencascade.wasm.wasm'), join(outDir, 'opencascade.wasm'));
  await writeFile(
    join(outDir, 'README.txt'),
    'Local control artifacts copied from opencascade.js@1.1.1. Generated/ignored; do not commit.\n',
  );
  console.log(`staged ${packageName} into public/vendor/opencascade`);
} finally {
  await rm(scratch, { recursive: true, force: true });
}
