#!/usr/bin/env node
// Generate TypeScript union of all i18n keys used by Cook Web
// Writes src/cook-web/src/types/i18n-keys.d.ts

const fs = require('fs');
const path = require('path');

const ROOT = path.resolve(__dirname, '..');
const I18N = path.join(ROOT, 'src', 'i18n');
const COOK_TYPES = path.join(ROOT, 'src', 'cook-web', 'src', 'types');
const OUT_FILE = path.join(COOK_TYPES, 'i18n-keys.d.ts');

function isObject(v) {
  return v && typeof v === 'object' && !Array.isArray(v);
}

function flatten(obj, prefix, out) {
  if (isObject(obj)) {
    const ns = obj.__namespace__ || prefix;
    const flat = obj.__flat__;
    if (isObject(flat)) {
      for (const k of Object.keys(flat)) {
        const key = ns ? `${ns}.${k}` : k;
        if (typeof flat[k] === 'string') out.add(key);
      }
    }
    for (const [k, v] of Object.entries(obj)) {
      if (k === '__namespace__' || k === '__flat__') continue;
      const next = ns ? `${ns}.${k}` : k;
      flatten(v, next, out);
    }
  } else if (typeof obj === 'string' && prefix) {
    out.add(prefix);
  }
}

function collectKeys() {
  const locales = fs.readdirSync(I18N).filter((d) => !d.startsWith('.'));
  if (locales.length === 0) return [];
  // Use the first locale as the reference (en-US recommended)
  const ref = path.join(I18N, locales[0]);
  const files = [];
  function walk(p) {
    for (const e of fs.readdirSync(p, { withFileTypes: true })) {
      if (e.name.startsWith('.')) continue;
      const fp = path.join(p, e.name);
      if (e.isDirectory()) walk(fp);
      else if (e.isFile() && e.name.endsWith('.json')) files.push(fp);
    }
  }
  walk(ref);

  const keys = new Set();
  for (const f of files) {
    const data = JSON.parse(fs.readFileSync(f, 'utf-8'));
    const rel = path.relative(ref, f).replace(/\\/g, '/').replace(/\.json$/, '');
    const ns = rel.replace(/\//g, '.');
    // Infer namespace from file path, but prefer __namespace__ if present
    flatten(data, ns, keys);
  }
  return Array.from(keys).sort();
}

function writeTypes(keys) {
  if (!fs.existsSync(COOK_TYPES)) fs.mkdirSync(COOK_TYPES, { recursive: true });
  const union = keys.map((k) => `  | '${k}'`).join('\n');
  const content = `// Auto-generated by scripts/generate_i18n_keys.js\nexport type I18nKey =\n${union || '  never'};\n`;
  fs.writeFileSync(OUT_FILE, content);
  console.log(`Wrote ${OUT_FILE} with ${keys.length} keys`);
}

writeTypes(collectKeys());
