import { readdir, readFile, writeFile } from "node:fs/promises";
import path from "node:path";

const project = path.resolve(new URL("..", import.meta.url).pathname);
const factorioData = process.env.FACTORIO_DATA ?? path.resolve(project, "../../vendor-official/extracted/data");
const locales = ["en", "de", "es-ES", "fr", "it", "ja", "ru", "zh-CN", "zh-TW"];
const mods = ["core", "base", "elevated-rails", "quality", "recycler", "space-age"];
const wantedSections = new Set([
  "item-name", "fluid-name", "entity-name", "equipment-name", "tile-name",
  "recipe-name", "recipe-category-name", "item-subgroup-name", "item-group-name",
  "quality-name", "space-location-name", "technology-name",
]);

function parseCfg(text, target) {
  let section = "";
  for (const rawLine of text.replace(/^\uFEFF/, "").split(/\r?\n/)) {
    const line = rawLine.trim();
    if (!line || line.startsWith(";") || line.startsWith("#")) continue;
    const heading = line.match(/^\[([^\]]+)\]$/);
    if (heading) {
      section = heading[1];
      continue;
    }
    if (!wantedSections.has(section)) continue;
    const separator = line.indexOf("=");
    if (separator < 1) continue;
    const key = line.slice(0, separator).trim();
    const value = line.slice(separator + 1).trim();
    if (!target[section]) target[section] = {};
    target[section][key] = value;
  }
}

const output = {};
for (const locale of locales) {
  const sections = {};
  for (const mod of mods) {
    const directory = path.join(factorioData, mod, "locale", locale);
    let names = [];
    try {
      names = (await readdir(directory)).filter((name) => name.endsWith(".cfg")).sort();
    } catch {
      continue;
    }
    for (const name of names) parseCfg(await readFile(path.join(directory, name), "utf8"), sections);
  }
  output[locale] = sections;
}

await writeFile(
  path.join(project, "app/data/official-locales.json"),
  JSON.stringify(output) + "\n",
);
console.log(`official-locales.json: ${locales.length} locales`);
