#!/usr/bin/env node
import fs from 'fs';
import path from 'path';

const serviceRoot = process.env.TEMPLATE_SERVICE_ROOT || '/var/www/vigthoria-template-service';
const meta = JSON.parse(fs.readFileSync(path.join(serviceRoot, 'metadata/templates.json'), 'utf8'));
const index = {};

for (const t of meta.templates) {
  const fp = path.join(serviceRoot, t.filePath);
  const vars = new Set(['TITLE', 'COMPANY_NAME']);
  if (fs.existsSync(fp)) {
    const html = fs.readFileSync(fp, 'utf8');
    for (const m of html.matchAll(/\{\{([A-Z0-9_]+)\}\}/g)) vars.add(m[1]);
  }
  index[t.id] = { category: t.category, variables: [...vars].sort(), tags: t.tags || [] };
}

const out = {
  generatedAt: new Date().toISOString(),
  count: Object.keys(index).length,
  templates: index,
};

const dest = path.join(process.cwd(), 'src/lib/template-variable-index.json');
fs.writeFileSync(dest, JSON.stringify(out, null, 2));
console.log(`Wrote ${out.count} templates to ${dest}`);
