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

const ROOT = path.resolve(__dirname, '..');
const LOCALES_DIR = path.join(ROOT, 'src', 'i18n', 'locales');
const BASE_LOCALE = 'de.json';
const CORE_NAMESPACES = [
  'common',
  'navigation',
  'club',
  'members',
  'diary',
  'trainingStats',
  'courtDrawingTool'
];

const BATCHES = {
  A: ['fr', 'es'],
  B: ['it', 'pl'],
  C: ['ja', 'zh'],
  D: ['th', 'tl', 'fil']
};

function loadJson(filePath) {
  return JSON.parse(fs.readFileSync(filePath, 'utf8'));
}

function flatten(obj, prefix = '', result = {}) {
  for (const [key, value] of Object.entries(obj || {})) {
    const nextKey = prefix ? `${prefix}.${key}` : key;
    if (value && typeof value === 'object' && !Array.isArray(value)) {
      flatten(value, nextKey, result);
    } else {
      result[nextKey] = value;
    }
  }
  return result;
}

function pickNamespaces(source) {
  return Object.fromEntries(CORE_NAMESPACES.map(namespace => [namespace, source[namespace] || {}]));
}

function statusFor(localeFile, baseFlat) {
  const locale = localeFile.replace(/\.json$/, '');
  const data = loadJson(path.join(LOCALES_DIR, localeFile));
  const flat = flatten(pickNamespaces(data));
  const keys = Object.keys(baseFlat);
  const missing = keys.filter(key => !(key in flat)).length;
  const sameAsDe = keys.filter(key => flat[key] === baseFlat[key]).length;
  const translated = keys.length - missing - sameAsDe;
  const coverage = ((keys.length - missing) / keys.length) * 100;
  const actualTranslationCoverage = (translated / keys.length) * 100;
  return { locale, missing, sameAsDe, translated, coverage, actualTranslationCoverage };
}

function printGroup(title, locales, baseFlat) {
  console.log(`\n# ${title}`);
  console.log('locale | translated | same as de | missing | core coverage | actual translation');
  console.log('--- | ---: | ---: | ---: | ---: | ---:');
  for (const locale of locales) {
    const result = statusFor(`${locale}.json`, baseFlat);
    console.log(
      `${result.locale} | ${result.translated} | ${result.sameAsDe} | ${result.missing} | ${result.coverage.toFixed(1)}% | ${result.actualTranslationCoverage.toFixed(1)}%`
    );
  }
}

function main() {
  const base = loadJson(path.join(LOCALES_DIR, BASE_LOCALE));
  const baseFlat = flatten(pickNamespaces(base));

  printGroup('Batch A', BATCHES.A, baseFlat);
  printGroup('Batch B', BATCHES.B, baseFlat);
  printGroup('Batch C', BATCHES.C, baseFlat);
  printGroup('Batch D', BATCHES.D, baseFlat);
}

main();
