#!/usr/bin/env node
// Scans packages/web/components/renderers/*/manifest.ts and generates
// packages/web/lib/renderers/index.ts with auto-discovered imports.
//
// Run: node scripts/gen-renderer-index.js
// Hooked into: npm run build (via prebuild)

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

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const renderersDir = path.resolve(__dirname, '../packages/web/components/renderers');
const outputFile = path.resolve(__dirname, '../packages/web/lib/renderers/index.ts');

// Scan for manifest.ts in immediate subdirectories
const dirs = fs.readdirSync(renderersDir, { withFileTypes: true })
  .filter(d => d.isDirectory())
  .filter(d => fs.existsSync(path.join(renderersDir, d.name, 'manifest.ts')))
  .map(d => d.name)
  .sort();

// Opt-in-only renderers (match: () => false) go last for consistent ordering.
const LAST = new Set(['graph']);
const sorted = [
  ...dirs.filter(d => !LAST.has(d)),
  ...dirs.filter(d => LAST.has(d)),
];

if (dirs.length === 0) {
  console.error('No manifest.ts files found in', renderersDir);
  process.exit(1);
}

// kebab-case → camelCase
function toCamel(s) {
  return s.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
}

const imports = sorted.map(dir => {
  const varName = toCamel(dir);
  return `import { manifest as ${varName} } from '@/components/renderers/${dir}/manifest';`;
}).join('\n');

const varNames = sorted.map(toCamel);

const code = `/**
 * AUTO-GENERATED by scripts/gen-renderer-index.js — do not edit manually.
 * To regenerate: node scripts/gen-renderer-index.js
 */
import { registerRenderer } from './registry';
${imports}

const manifests = [
  ${varNames.join(', ')},
];

for (const m of manifests) {
  registerRenderer(m);
}
`;

fs.writeFileSync(outputFile, code, 'utf-8');
console.log(`Generated ${path.relative(process.cwd(), outputFile)} with ${dirs.length} renderers: ${dirs.join(', ')}`);
