import { mkdir } from 'node:fs/promises';
import { dirname, join, relative } from 'node:path';
import { fileURLToPath } from 'node:url';
import { spawnSync } from 'node:child_process';

// Usage: node docs/scripts/build-typst-tz.mjs
// Source: docs/tz-fregat.typ
// Output: docs/export/tz-fregat.pdf

const __dirname = dirname(fileURLToPath(import.meta.url));
const docsDir = join(__dirname, '..');
const sourceFile = join(docsDir, 'tz-fregat.typ');
const exportDir = join(docsDir, 'export');
const pdfFile = join(exportDir, 'tz-fregat.pdf');

await mkdir(exportDir, { recursive: true });

const compileResult = spawnSync('typst', [
  'compile',
  '--root',
  '.',
  relative(docsDir, sourceFile),
  relative(docsDir, pdfFile),
], {
  cwd: docsDir,
  encoding: 'utf8',
});

if (compileResult.status !== 0) {
  process.stderr.write(compileResult.stderr);
  process.stderr.write(compileResult.stdout);
  throw new Error('Typst PDF build failed');
}

process.stdout.write(`Generated ${relative(docsDir, pdfFile)}\n`);
