#!/usr/bin/env node
/**
 * Build script for Oliver DeckForge documentation PDFs.
 *
 * 1. Renders Mermaid diagrams to PNG via @mermaid-js/mermaid-cli (mmdc)
 * 2. Converts the resulting Markdown (with images) to styled PDFs via md-to-pdf
 * 3. Cleans up intermediate files
 *
 * Usage:  node docs/build-pdfs.mjs
 */

import { execSync } from 'child_process';
import { readdirSync, unlinkSync, existsSync } from 'fs';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';

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

const sources = [
  '01-User-Manual.md',
  '02-System-Administration-Guide.md',
];

for (const file of sources) {
  const input = join(__dirname, file);
  const rendered = join(__dirname, file.replace('.md', '-rendered.md'));
  const renderedPdf = rendered.replace('.md', '.pdf');
  const finalPdf = join(__dirname, file.replace('.md', '.pdf'));

  console.log(`\n=== ${file} ===`);

  // 1. Pre-render Mermaid diagrams → PNG, output modified markdown
  console.log('  [1/3] Rendering Mermaid diagrams...');
  execSync(
    `npx -y @mermaid-js/mermaid-cli -i "${input}" -o "${rendered}" -e png --scale 2`,
    { cwd: __dirname, stdio: 'inherit' },
  );

  // 2. Convert rendered markdown → PDF
  console.log('  [2/3] Converting to PDF...');
  execSync(`npx -y md-to-pdf "${rendered}"`, {
    cwd: __dirname,
    stdio: 'inherit',
  });

  // 3. Move PDF to final name and clean up temp files
  console.log('  [3/3] Cleaning up...');
  execSync(`mv "${renderedPdf}" "${finalPdf}"`);

  // Remove rendered markdown
  if (existsSync(rendered)) unlinkSync(rendered);

  // Remove generated diagram PNGs
  const prefix = file.replace('.md', '-rendered-');
  readdirSync(__dirname)
    .filter((f) => f.startsWith(prefix) && f.endsWith('.png'))
    .forEach((f) => unlinkSync(join(__dirname, f)));

  console.log(`  -> ${file.replace('.md', '.pdf')} created`);
}

console.log('\nDone.');
