"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.preservation = void 0;
const toml = __importStar(require("@iarna/toml"));
exports.preservation = {
    markdown: {
        rewrite(options) {
            let nextContent = options.currentContent;
            for (const section of options.sections ?? []) {
                nextContent = rewriteMarkdownSection(nextContent, section);
            }
            return {
                contents: ensureTrailingNewline(nextContent),
                preservationMode: 'semantic',
                exactFormattingPreserved: false,
            };
        },
    },
    toml: {
        rewrite(options) {
            const parsedCurrent = parseTomlDocument(options.currentContent);
            const nextDocument = mergeTomlDocuments(parsedCurrent, options.values);
            for (const key of options.deleteKeys ?? []) {
                delete nextDocument[key];
            }
            return {
                contents: formatTomlDocument(nextDocument),
                preservationMode: 'semantic',
                exactFormattingPreserved: false,
            };
        },
    },
};
function rewriteMarkdownSection(content, rewrite) {
    const sections = matchMarkdownSections(content);
    const existingSection = sections.find((section) => section.heading === rewrite.heading && (rewrite.level === undefined || section.level === rewrite.level));
    if (existingSection !== undefined) {
        const replacement = buildMarkdownSection(existingSection.headingLine, rewrite.content);
        return content.slice(0, existingSection.startIndex) + replacement + content.slice(existingSection.endIndex);
    }
    if (rewrite.appendIfMissing === false) {
        return content;
    }
    const headingLine = `${'#'.repeat(rewrite.level ?? 2)} ${rewrite.heading}`;
    const replacement = buildMarkdownSection(headingLine, rewrite.content);
    const trimmedContent = content.replace(/\n*$/, '');
    if (trimmedContent === '') {
        return replacement;
    }
    return `${trimmedContent}\n\n${replacement}`;
}
function matchMarkdownSections(content) {
    const matches = Array.from(content.matchAll(/^(#{1,6})[ \t]+(.+?)[ \t]*$/gm));
    return matches.map((match, index) => {
        const headingLine = match[0];
        const nextMatch = matches[index + 1];
        return {
            heading: match[2],
            level: match[1].length,
            headingLine,
            startIndex: match.index ?? 0,
            endIndex: nextMatch?.index ?? content.length,
        };
    });
}
function buildMarkdownSection(headingLine, content) {
    const trimmedContent = content.replace(/^\n+|\n+$/g, '');
    if (trimmedContent === '') {
        return `${headingLine}\n`;
    }
    return `${headingLine}\n\n${trimmedContent}\n\n`;
}
function parseTomlDocument(currentContent) {
    if (currentContent.trim() === '') {
        return {};
    }
    const parsedDocument = toml.parse(currentContent);
    if (typeof parsedDocument !== 'object' || parsedDocument === null || Array.isArray(parsedDocument)) {
        return {};
    }
    return parsedDocument;
}
function mergeTomlDocuments(currentDocument, updates) {
    const nextDocument = { ...currentDocument };
    for (const [key, value] of Object.entries(updates)) {
        const currentValue = nextDocument[key];
        if (isPlainObject(currentValue) && isPlainObject(value)) {
            nextDocument[key] = mergeTomlDocuments(currentValue, value);
            continue;
        }
        nextDocument[key] = value;
    }
    return nextDocument;
}
function formatTomlDocument(document) {
    const contents = toml.stringify(document);
    return ensureTrailingNewline(contents);
}
function isPlainObject(value) {
    return typeof value === 'object' && value !== null && !Array.isArray(value);
}
function ensureTrailingNewline(contents) {
    return contents.endsWith('\n') ? contents : `${contents}\n`;
}
