// Codegen: packages/myco/src/symbionts/templates.generated.ts
//
// Embeds every file under src/symbionts/templates/ as a string keyed by its
// relative path. The installer's `readTemplateFile(relPath)` prefers this
// bundled map over the filesystem lookup — needed because the Bun-compiled
// binary can't fs.readFileSync paths that live inside the /$bunfs/ virtual
// filesystem. In dev mode (tsx / bun run) the bundled map is still correct
// because it's regenerated as part of `npm run codegen`.
//
// Run manually: npx tsx packages/myco/scripts/gen-templates.mjs
// Wired into `npm run codegen`.

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

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const PKG_ROOT = path.resolve(__dirname, '..');
const TEMPLATES_DIR = path.resolve(PKG_ROOT, 'src/symbionts/templates');
const OUTPUT = path.resolve(PKG_ROOT, 'src/symbionts/templates.generated.ts');

function walk(dir, acc = []) {
  for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
    const full = path.join(dir, entry.name);
    if (entry.isDirectory()) walk(full, acc);
    else if (entry.isFile()) acc.push(full);
  }
  return acc;
}

const files = walk(TEMPLATES_DIR).sort();
const entries = files.map((abs) => {
  const rel = path.relative(TEMPLATES_DIR, abs).split(path.sep).join('/');
  const body = fs.readFileSync(abs, 'utf-8');
  return [rel, body];
});

const serialized = entries
  .map(([rel, body]) => `  ${JSON.stringify(rel)}: ${JSON.stringify(body)},`)
  .join('\n');

const output = `// AUTO-GENERATED by scripts/gen-templates.mjs — DO NOT EDIT.
// Regenerate via \`npm run codegen\`.

export const BUNDLED_TEMPLATES: Readonly<Record<string, string>> = {
${serialized}
};
`;

fs.writeFileSync(OUTPUT, output, 'utf-8');
process.stdout.write(`[gen-templates] wrote ${path.relative(PKG_ROOT, OUTPUT)} (${entries.length} files)\n`);
