// scripts/sync-translations.js
import fs from "fs";
import path from "path";

const locales = ["en", "es", "de"];

const docsDir = path.join(process.cwd(), "../lstDocs/docs"); // canonical English docs
const i18nDir = path.join(process.cwd(), "../lstDocs/i18n"); // output localized docs
const langDir = path.join(process.cwd(), "../lang"); // json translations

// load translations
const translations = {};
for (const locale of locales) {
    const filePath = path.join(langDir, `${locale}.json`);
    translations[locale] = JSON.parse(fs.readFileSync(filePath, "utf8"));
}

// lookup helper with English fallback
function t(key, locale) {
    return translations[locale][key] || translations["en"][key] || key;
}

// copy directory recursively
function copyDir(src, dest) {
    if (!fs.existsSync(src)) return;
    fs.mkdirSync(dest, { recursive: true });
    for (const item of fs.readdirSync(src)) {
        const s = path.join(src, item);
        const d = path.join(dest, item);
        const stat = fs.statSync(s);
        if (stat.isDirectory()) copyDir(s, d);
        else fs.copyFileSync(s, d);
    }
}

// recursive doc processor
function processDir(srcDir, relDir = "") {
    for (const item of fs.readdirSync(srcDir, { withFileTypes: true })) {
        const srcPath = path.join(srcDir, item.name);
        const relPath = path.join(relDir, item.name);

        if (item.isDirectory()) {
            processDir(srcPath, relPath);
            continue;
        }

        if (item.isFile() && item.name.endsWith(".md")) {
            const baseContent = fs.readFileSync(srcPath, "utf8");

            for (const locale of locales) {
                // replace keys with translations
                const localizedContent = baseContent.replace(
                    /([a-z]+(\.[a-z]+)+)/g,
                    (match) => t(match, locale)
                );

                // output directory preserves structure
                const outDir = path.join(
                    i18nDir,
                    locale,
                    "docusaurus-plugin-content-docs/current",
                    relDir
                );
                fs.mkdirSync(outDir, { recursive: true });

                const outFile = path.join(outDir, item.name);
                fs.writeFileSync(outFile, localizedContent, "utf8");
            }
        }

        // if there's an "img" folder alongside docs, copy it once for each locale
        if (item.isDirectory() && item.name === "img") {
            for (const locale of locales) {
                const outDir = path.join(
                    i18nDir,
                    locale,
                    "docusaurus-plugin-content-docs/current",
                    relDir,
                    "img"
                );
                copyDir(srcPath, outDir);
            }
        }
    }
}

// run
processDir(docsDir);
