import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const PACKAGE_ROOT = path.resolve(__dirname, '..');
const PROMPTS_DIR = path.resolve(PACKAGE_ROOT, 'src/prompts');
const TEMPLATES_DIR = path.resolve(PACKAGE_ROOT, 'src/templates');
const OUTPUT_PATH = path.resolve(PACKAGE_ROOT, 'src/static-assets.generated.ts');

function readMarkdownMap(dir: string): Record<string, string> {
  return Object.fromEntries(
    fs.readdirSync(dir)
      .filter((file) => file.endsWith('.md'))
      .sort()
      .map((file) => [path.basename(file, '.md'), fs.readFileSync(path.join(dir, file), 'utf-8')]),
  );
}

function main(): void {
  const prompts = readMarkdownMap(PROMPTS_DIR);
  const templates = readMarkdownMap(TEMPLATES_DIR);

  const output = `// AUTO-GENERATED by scripts/gen-static-assets.ts — DO NOT EDIT.
// Run \`npm run codegen\` to regenerate.
//
// Package-owned markdown assets bundled into code for the Bun-compiled
// binary path. These files live under \`src/\` in the repo, but the compiled
// binary cannot rely on runtime filesystem reads inside \`/$bunfs/\`.

export const BUNDLED_PROMPTS: Readonly<Record<string, string>> = ${JSON.stringify(prompts, null, 2)} as const;

export const BUNDLED_MARKDOWN_TEMPLATES: Readonly<Record<string, string>> = ${JSON.stringify(templates, null, 2)} as const;
`;

  fs.writeFileSync(OUTPUT_PATH, output, 'utf-8');
  process.stdout.write(
    `[gen-static-assets] wrote ${path.relative(PACKAGE_ROOT, OUTPUT_PATH)} (${Object.keys(prompts).length} prompts, ${Object.keys(templates).length} templates)\n`,
  );
}

main();
