/**
 * Generate `src/data/skill-versions.json` (bundle-only) and
 * `src/data/skill-changelog.ts` from the skills/ source tree.
 *
 * Bundle versioning model — single source of truth in `skills/VERSION`.
 * No per-skill semver. The whole `skills/` directory ships as one
 * versioned bundle. The dashboard / CLI compare a single number to
 * detect drift.
 *
 * Run:
 *   pnpm skills:build
 */

import { readFileSync, readdirSync, mkdirSync, writeFileSync, statSync } from 'node:fs';
import { join, dirname } from 'node:path';

const ROOT = process.cwd();
const SKILLS_DIR = join(ROOT, 'skills');
const OUT_PATH = join(ROOT, 'src/data/skill-versions.json');

function main(): void {
  const bundle = readFileSync(join(SKILLS_DIR, 'VERSION'), 'utf8').trim();

  const entries = readdirSync(SKILLS_DIR, { withFileTypes: true })
    .filter((d) => d.isDirectory())
    .map((d) => d.name)
    .filter((name) => {
      try {
        statSync(join(SKILLS_DIR, name, 'SKILL.md'));
        return true;
      } catch {
        return false;
      }
    })
    .sort();

  mkdirSync(dirname(OUT_PATH), { recursive: true });
  const out = { bundleVersion: bundle, skills: entries };
  writeFileSync(OUT_PATH, JSON.stringify(out, null, 2) + '\n', 'utf8');

  // Embed CHANGELOG.md into a TS module so a future /skill-versions
  // endpoint (or the landing /docs/skills page at build-time) can serve
  // it without a runtime fs read.
  const changelogPath = join(SKILLS_DIR, 'CHANGELOG.md');
  let changelogText = '';
  try {
    changelogText = readFileSync(changelogPath, 'utf8');
  } catch {
    changelogText = '# Skills Changelog\n\n(empty)\n';
  }
  const tsOut = join(ROOT, 'src/data/skill-changelog.ts');
  const escaped = changelogText.replace(/\\/g, '\\\\').replace(/`/g, '\\`').replace(/\$/g, '\\$');
  writeFileSync(
    tsOut,
    `// Auto-generated by scripts/build-skill-versions.ts — do not edit.\n` +
      `export const skillChangelog = \`${escaped}\`;\n`,
    'utf8',
  );

  // eslint-disable-next-line no-console
  console.log(`wrote ${OUT_PATH} — bundle ${bundle}, ${entries.length} skills`);
  // eslint-disable-next-line no-console
  console.log(`wrote ${tsOut} — ${changelogText.length} bytes`);
}

main();
