/**
 * CLI Script: Normalize Atlas JSON
 * Rewrites bundled atlas image references into normalized atlas-relative paths so
 * imports and image resolution remain consistent across environments.
 */
const fs = require('fs');
const path = require('path');

const { createAtlasImageResolver } = require('../utils/atlasImageResolver');
const { ATLAS_TRANSLATION_SUFFIX } = require('../utils/atlasImportUtils');

const backendDir = path.join(__dirname, '..');
const atlasesDir = path.join(backendDir, 'data', 'atlases');
const imagesDir = path.join(backendDir, 'public', 'images');
const resolveAtlasImage = createAtlasImageResolver(imagesDir);

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

function normalizeAtlas(atlas) {
    for (const section of atlas.sections || []) {
        for (const trait of section.traits || section.znaky || []) {
            for (const option of trait.options || []) {
                option.images = (option.images || []).map((imageReference) => {
                    try {
                        return resolveAtlasImage.toAtlasReference(imageReference);
                    } catch (error) {
                        throw new Error(`${atlas.id}: ${error.message}`);
                    }
                });
            }
        }
    }

    return atlas;
}

function normalizeAllAtlases() {
    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 filePath = path.join(atlasesDir, fileName);
        const atlas = readJsonFile(filePath);
        const normalizedAtlas = normalizeAtlas(atlas);
        fs.writeFileSync(filePath, `${JSON.stringify(normalizedAtlas, null, 4)}\n`, 'utf8');
        console.log(`Normalized ${fileName}`);
    }
}

normalizeAllAtlases();