"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.canonicalizeStepsForSave = canonicalizeStepsForSave;
const variableCanonical_1 = require("../variableCanonical");
const SYSTEM_ALIASES = Object.values((0, variableCanonical_1.flattenVariables)(variableCanonical_1.SYSTEM_DEFAULT_VARIABLES))
    .filter((v) => Boolean(v.humanizedName))
    .map((v) => ({
    from: `{{@${v.humanizedName}}}`,
    to: `{{@${v.name}}}`,
}));
function canonicalizeStepsForSave(steps) {
    if (steps === undefined) {
        return { steps, report: { rewrites: [], total: 0 } };
    }
    const serialized = JSON.stringify(steps);
    const rewrites = [];
    let total = 0;
    for (const { from, to } of SYSTEM_ALIASES) {
        const count = countOccurrences(serialized, from);
        if (count > 0) {
            rewrites.push({ from, to, count });
            total += count;
        }
    }
    if (total === 0) {
        return { steps, report: { rewrites: [], total: 0 } };
    }
    const transformed = (0, variableCanonical_1.canonicalizeVariablePatternsInObject)(variableCanonical_1.SYSTEM_DEFAULT_VARIABLES, steps);
    return { steps: transformed, report: { rewrites, total } };
}
function countOccurrences(haystack, needle) {
    let count = 0;
    let idx = 0;
    while ((idx = haystack.indexOf(needle, idx)) !== -1) {
        count++;
        idx += needle.length;
    }
    return count;
}
