/**
 * CLI Script: Split Atlas Translations
 * Converts legacy bilingual atlas files into an English source JSON plus a Czech
 * translation sidecar consumed by the import utilities.
 */
const fs = require('fs');
const path = require('path');

const {
    ATLAS_TRANSLATION_SUFFIX,
    getAtlasTranslationFilePath,
} = require('../utils/atlasImportUtils');

const atlasesDir = path.join(__dirname, '..', 'data', 'atlases');

function readJsonFile(filePath) {
    const fileContents = fs.readFileSync(filePath, 'utf8').replace(/^\uFEFF/, '');
    return JSON.parse(fileContents);
}

function writeJsonFile(filePath, value) {
    fs.writeFileSync(filePath, `${JSON.stringify(value, null, 4)}\n`, 'utf8');
}

function hasLegacyLocalizedAtlasFields(atlas) {
    return Boolean(atlas && (atlas.label_cs || atlas.label_en || atlas.popis_cs || atlas.popis_en));
}

function splitAtlas(atlas) {
    return {
        englishAtlas: {
            id: atlas.id,
            label: atlas.label_en,
            description: atlas.popis_en || '',
            sections: (atlas.sections || []).map(section => ({
                name: section.nazev_en,
                traits: (section.znaky || []).map(trait => ({
                    id: trait.id,
                    label: trait.label_en,
                    description: trait.popis_en || '',
                    options: (trait.options || []).map(option => ({
                        label: option.label_en,
                        images: Array.isArray(option.images) ? option.images : [],
                    })),
                })),
            })),
        },
        czechTranslations: {
            id: atlas.id,
            label: atlas.label_cs,
            description: atlas.popis_cs || '',
            sections: (atlas.sections || []).map(section => ({
                name: section.nazev_cs,
                traits: (section.znaky || []).map(trait => ({
                    id: trait.id,
                    label: trait.label_cs,
                    description: trait.popis_cs || '',
                    options: (trait.options || []).map(option => ({
                        label: option.label_cs,
                    })),
                })),
            })),
        },
    };
}

function splitAllAtlases() {
    const atlasFiles = fs.readdirSync(atlasesDir)
        .filter(fileName => fileName.endsWith('.json'))
        .filter(fileName => !fileName.endsWith(ATLAS_TRANSLATION_SUFFIX))
        .sort((left, right) => left.localeCompare(right));

    for (const fileName of atlasFiles) {
        const atlasFilePath = path.join(atlasesDir, fileName);
        const atlas = readJsonFile(atlasFilePath);

        if (!hasLegacyLocalizedAtlasFields(atlas)) {
            console.log(`Skipped ${fileName} (already split)`);
            continue;
        }

        const { englishAtlas, czechTranslations } = splitAtlas(atlas);
        const translationFilePath = getAtlasTranslationFilePath(atlasFilePath);

        writeJsonFile(atlasFilePath, englishAtlas);
        writeJsonFile(translationFilePath, czechTranslations);
        console.log(`Split ${fileName} -> ${path.basename(translationFilePath)}`);
    }
}

splitAllAtlases();