#!/usr/bin/env node
import { parseArgs } from 'node:util'
import { fontStyleBlock } from '../src/excalidraw/font-style-block.js'
import { processFile } from '../src/excalidraw/stages.js'

const HELP = `
Usage: excalidraw-stages <file.excalidraw> [...]

Generate cumulative SVG stages from a single Excalidraw source file.

Each frame in the source file (named with a numeric prefix, e.g. "01-problem",
"02-loop") becomes one SVG export. Each export accumulates all frames up to
that point, so elements introduced in frame 1 persist through all later frames.

Elements not assigned to a frame are treated as drafts and excluded from all
exports.

Arguments:
  file.excalidraw  One or more Excalidraw source files. Glob patterns are
                   expanded by your shell (e.g. topics/**/*.excalidraw).

Options:
  --embed-fonts    Base64-embed Excalifont and Cascadia into each SVG so it
                   is fully self-contained. Default: reference fonts by
                   family name only (smaller files; the host page must
                   provide the @font-face declarations — the Marp plugin
                   does this).
  --init           Print a <style> block with @font-face declarations for
                   Excalifont and Cascadia. Paste once into your host HTML
                   so external-font SVGs render correctly outside Marp.

Output:
  Each source file gets its own output directory named <slug>__stages/,
  created alongside the source file. Frame SVGs are named after the frame:
    diagram.excalidraw → diagram__stages/01-overview.svg, diagram__stages/02-loop.svg, ...
  A frameless diagram outputs a single diagram__stages/image.svg.

Examples:
  excalidraw-stages diagram.excalidraw
  excalidraw-stages topics/**/*.excalidraw
`.trimStart()

const { values, positionals: files } = parseArgs({
  args: process.argv.slice(2),
  options: {
    'embed-fonts': { type: 'boolean', default: false },
    'init':        { type: 'boolean', default: false },
    'help':        { type: 'boolean', default: false, short: 'h' },
  },
  allowPositionals: true,
})

if (values.help) {
  process.stdout.write(HELP)
  process.exit(0)
}

if (values.init) {
  process.stdout.write(fontStyleBlock() + '\n')
  process.exit(0)
}

if (!files.length) {
  process.stderr.write('Usage: excalidraw-stages <file.excalidraw> [...]\nRun with --help for more information.\n')
  process.exit(1)
}

const embedFonts = values['embed-fonts']

for (const file of files) {
  try {
    const result = await processFile(file, { embedFonts })
    console.log(result === 'up-to-date' ? `${file}: up to date` : `Built: ${file}`)
  } catch (err) {
    console.error(`Error: ${err.message}`)
    process.exit(1)
  }
}
