// Generates docs/superpowers/index.md from docs/superpowers/manifest.yaml.
// Usage: node scripts/gen-design-index.mjs
import { readFileSync, writeFileSync } from 'node:fs';
import { dirname, resolve, join } from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { createRequire } from 'node:module';
import { renderIndex } from './lib/design-index.mjs';

const __dirname = dirname(fileURLToPath(import.meta.url));
const SP = resolve(__dirname, '../docs/superpowers');

// `yaml` lives in ui/node_modules — resolve relative to ui/package.json,
// exactly like scripts/validate-design-docs.mjs does. Guard the resolution so a
// missing `yaml` doesn't throw at import time (which would break any module that
// statically imports buildIndex, e.g. validate-design-docs.mjs --check).
let parseYaml = null;
try {
  const require = createRequire(pathToFileURL(resolve(__dirname, '../ui/package.json')));
  ({ parse: parseYaml } = await import(pathToFileURL(require.resolve('yaml')).href));
} catch {
  // resolved lazily-checked in buildIndex()
}

export function buildIndex() {
  if (!parseYaml) throw new Error("design-index gen: cannot load 'yaml' from ui/node_modules — run `npm --prefix ui install`");
  const manifest = parseYaml(readFileSync(join(SP, 'manifest.yaml'), 'utf-8')) ?? { docs: [] };
  return renderIndex(manifest.docs ?? []);
}

if (import.meta.url === pathToFileURL(process.argv[1]).href) {
  writeFileSync(join(SP, 'index.md'), buildIndex(), 'utf-8');
  console.log('gen: wrote docs/superpowers/index.md');
}
