export function fillTemplates(templates) {
    const json = JSON.parse(templates);
    const $fragments = json.$fragments;
    if (!$fragments) {
        delete json.$schema;
        return json;
    }
    const patchedJson = patchEntries(json, $fragments);
    delete patchedJson.$schema;
    delete patchedJson.$fragments;
    return patchedJson;
}
function patchEntries(json, fragments) {
    if (typeof json !== "object" || json === null) {
        return json;
    }
    if (Array.isArray(json)) {
        return json.map((item) => patchEntries(item, fragments));
    }
    if (typeof json === "object") {
        let patchedJson = {};
        for (const key in json) {
            if (Object.prototype.hasOwnProperty.call(json, key)) {
                const castedJson = json;
                const value = castedJson[key];
                const isFragmentRef = key === "$ref";
                const isValidRef = typeof value === "string" && value.startsWith("#/$fragments/");
                if (isFragmentRef && isValidRef) {
                    const fragmentName = value.replace("#/$fragments/", "");
                    if (Object.prototype.hasOwnProperty.call(fragments, fragmentName)) {
                        const patchedEntries = patchEntries(fragments[fragmentName], fragments);
                        patchedJson = { ...patchedJson, ...patchedEntries };
                        delete patchedJson.$ref;
                    }
                    else {
                        patchedJson[key] = value;
                    }
                }
                else {
                    patchedJson[key] = patchEntries(value, fragments);
                }
            }
        }
        return patchedJson;
    }
    return json;
}
export function groupTemplates(formats) {
    return Object.entries(formats).reduce((acc, [code, value]) => {
        const { group, groups = [] } = value;
        const item = { code, ...value };
        const allGroups = group ? [group, ...groups] : groups;
        const formatedGroups = allGroups.reduce((subAcc, group) => {
            return {
                ...subAcc,
                [group]: acc[group] === undefined
                    ? [item]
                    : [...acc[group], item],
            };
        }, {});
        return {
            ...acc,
            ...formatedGroups,
        };
    }, {});
}
