/*
 * Copyright 2026, Jaime Terrats.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
const START_RE = /<!-- setup-agents:block:start id="([^"]+)" version="([^"]+)" -->/g;
export function managedBlock(id, version, body) {
    return [
        `<!-- setup-agents:block:start id="${id}" version="${version}" -->`,
        body.trim(),
        `<!-- setup-agents:block:end id="${id}" -->`,
    ].join('\n');
}
export function updateManagedBlocks(existingContent, nextContent) {
    const existingBlocks = parseManagedBlocks(existingContent);
    const nextBlocks = parseManagedBlocks(nextContent);
    if (existingBlocks.length === 0 || nextBlocks.length === 0) {
        return { content: nextContent, applied: false, updatedBlockIds: [] };
    }
    const nextById = new Map(nextBlocks.map((block) => [block.id, block]));
    const matched = existingBlocks.filter((block) => nextById.has(block.id));
    if (matched.length === 0) {
        return { content: nextContent, applied: false, updatedBlockIds: [] };
    }
    let merged = existingContent;
    for (const block of [...matched].sort((a, b) => b.start - a.start)) {
        const nextBlock = nextById.get(block.id);
        merged = `${merged.slice(0, block.start)}${nextBlock.content}${merged.slice(block.end)}`;
    }
    return {
        content: merged,
        applied: true,
        updatedBlockIds: matched.map((block) => block.id),
    };
}
export function hasManagedBlocks(content) {
    return parseManagedBlocks(content).length > 0;
}
function parseManagedBlocks(content) {
    const blocks = [];
    START_RE.lastIndex = 0;
    for (let match = START_RE.exec(content); match; match = START_RE.exec(content)) {
        const [startMarker, id, version] = match;
        const endMarker = `<!-- setup-agents:block:end id="${id}" -->`;
        const endMarkerStart = content.indexOf(endMarker, match.index + startMarker.length);
        if (endMarkerStart === -1)
            continue;
        const end = endMarkerStart + endMarker.length;
        blocks.push({
            id,
            version,
            start: match.index,
            end,
            content: content.slice(match.index, end),
        });
    }
    return blocks;
}
//# sourceMappingURL=managed-blocks.js.map