"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const patch_1 = require("../../src/agents/tools/patch");
const diff_1 = require("diff");
describe("fixPatch", () => {
    it("should fix corrupted patches", async () => {
        const original = Array(10)
            .fill(null)
            .map(() => Math.random().toString(36).substring(2, 15))
            .join("\n") + "\n";
        const modified = original.split("\n");
        modified[Math.floor(Math.random() * 10)] += "_changed";
        const newString = modified.join("\n");
        const patch = (0, diff_1.createTwoFilesPatch)("file.txt", "file.txt", original, newString);
        let corruptedPatch = patch.replace(/@@.*/, "@@ -1000,1 +1000,1 @@");
        const corruptedPatchLines = corruptedPatch.split("\n");
        let incorrectLine = true;
        let missingLine = true;
        let sawSubtraction = false;
        for (let i = 4; i < corruptedPatchLines.length; i++) {
            const line = corruptedPatchLines[i];
            if (line.startsWith("-")) {
                sawSubtraction = true;
                break;
            }
            if (line.startsWith(" ") && incorrectLine) {
                corruptedPatchLines[i] = "XXXX";
                incorrectLine = false;
                continue;
            }
            if (line.startsWith(" ") && missingLine) {
                delete corruptedPatchLines[i];
                missingLine = false;
                break;
            }
        }
        corruptedPatch = corruptedPatchLines.join("\n");
        const attempt = (0, diff_1.applyPatch)(original, corruptedPatch);
        console.log({ patch, corruptedPatch });
        let fixedPatch = (0, patch_1.fixPatch)(original, corruptedPatch);
        console.log({ patch, corruptedPatch, attempt, fixedPatch });
        const result = (0, diff_1.applyPatch)(original, fixedPatch);
        const header = fixedPatch.split("\n")[0];
        const originalHeader = patch
            .split("\n")
            .find((line) => line.startsWith("@@"));
        if (result !== newString) {
            fixedPatch = (0, patch_1.fixPatch)(original, corruptedPatch);
        }
        expect(result).toBe(newString);
    });
});
//# sourceMappingURL=corrupted.test.js.map