"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.buildConfig = buildConfig;
function naturalCompare(a, b) {
    // Split by dots and hyphens, compare numbers as numbers
    const regex = /(\d+|\D+)/g;
    const ax = a.match(regex);
    const bx = b.match(regex);
    for (let i = 0; i < Math.max(ax.length, bx.length); i++) {
        const an = parseInt(ax[i], 10);
        const bn = parseInt(bx[i], 10);
        if (!isNaN(an) && !isNaN(bn)) {
            if (an !== bn)
                return an - bn;
        }
        else if (ax[i] !== bx[i])
            return (ax[i] || "").localeCompare(bx[i] || "");
    }
    return 0;
}
/**
 * Crea la configuración y lista de ejercicios para un curso.
 *
 * @param bucket - Instancia de GCS Bucket donde está el curso.
 * @param courseSlug - Slug del curso a procesar.
 * @returns Promise con objeto { config, exercises } listo para usar.
 */
async function buildConfig(bucket, courseSlug) {
    const prefix = `courses/${courseSlug}/`;
    const [files] = await bucket.getFiles({ prefix });
    // 1) Leer learn.json
    const learnFile = files.find(f => f.name.endsWith("learn.json"));
    const [learnBuf] = await learnFile.download();
    const learnJson = JSON.parse(learnBuf.toString());
    // 2) Agrupar ejercicios
    const map = {};
    for (const file of files) {
        const parts = file.name.split("/");
        if (!parts.includes("exercises"))
            continue;
        const slug = parts[parts.indexOf("exercises") + 1];
        if (!map[slug]) {
            map[slug] = {
                title: slug,
                slug,
                graded: false,
                files: [],
                translations: {},
            };
        }
        const fname = parts.pop();
        const m = fname.match(/^readme(?:\.([a-z]{2}))?\.md$/i);
        if (m) {
            const lang = m[1] || "en";
            map[slug].translations[lang] = fname;
        }
        else {
            map[slug].files.push({
                name: fname,
                slug: fname,
                hidden: false,
            });
        }
    }
    const exercises = Object.values(map)
        .sort((a, b) => naturalCompare(a.slug, b.slug))
        .map((ex, i) => (Object.assign(Object.assign({}, ex), { position: i })));
    return {
        config: Object.assign({}, learnJson),
        exercises,
    };
}
