"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
require("source-map-support/register");
const diff_1 = require("diff");
const patcher_1 = require("../../agents/patcher/patcher");
const utils_1 = require("../../utils");
const patch_1 = require("../../agents/tools/patch");
const hashes_1 = require("../../hashes");
const services_1 = require("../../services");
const dataset = [];
class PatchTestAgent extends patcher_1.PatchingAgent {
    name = "PatchTestAgent";
    async getInitialMessages(userInput) {
        const baseMessages = await super.getInitialMessages(userInput);
        baseMessages.push({
            content: "We are testing the patch tool, attempt to use only that tool with the input provided in the user's message.",
            role: "user",
        });
        return baseMessages;
    }
    async processToolMessages(toolCall) {
        const toolMessages = await super.processToolMessages(toolCall);
        toolMessages.push({
            name: "finalAnswer",
            content: "Done",
        });
        return toolMessages;
    }
}
async function testDataset() {
    const patchAgent = new PatchTestAgent((0, services_1.services)());
    let successCount = 0;
    let attempts = 0;
    const testHash = "";
    const shuffled = dataset
        .map((value) => ({ value, sort: Math.random() }))
        .sort((a, b) => a.sort - b.sort)
        .map(({ value }) => value);
    for (const patchData of shuffled) {
        const hash = await (0, hashes_1.md5Hash)(patchData.patch);
        if (testHash && testHash !== hash) {
            continue;
        }
        const changes = (0, patch_1.parseHunks)(patchData.patch);
        const totalChanges = changes
            .map((hunk) => hunk.additions.length + hunk.subtractions.length)
            .reduce((a, b) => a + b, 0);
        if (totalChanges > 10) {
            continue;
        }
        async function testPatchFile(filePath, patch) {
            attempts++;
            const originalContent = patchData.before;
            const fixedPatch = (0, patch_1.fixPatch)(patchData.before, patch);
            const { validHunks, invalidHunks } = (0, patch_1.categorizeHunks)(originalContent, patch);
            const validPatch = (0, patch_1.hunksToPatch)(validHunks);
            const updatedContent = (0, diff_1.applyPatch)(originalContent, validPatch);
            const success = !!updatedContent && validHunks.length;
            await saveToolDiagnosticFiles(patchData, patch, fixedPatch, validPatch, success);
            if (success) {
                successCount++;
            }
            if (updatedContent === patchData.after ||
                fixedPatch === patchData.patch) {
                console.log("SUCCESS");
                console.log("EXACT MATCH");
            }
            else {
                console.log("AI SUGGESTED");
                console.log(patch);
                console.log("FIXED PATCH");
                console.log(fixedPatch);
                console.log("ACTUAL");
                console.log(patchData.patch);
                console.log("DID PATCH APPLY?", !!updatedContent);
            }
            if (!success) {
            }
            const invalidPatch = (0, patch_1.hunksToPatch)(invalidHunks);
            const invalidHunksMessage = invalidHunks.length
                ? `Patch Partially Applied: \n Invalid Hunks: \n${invalidPatch} `
                : "";
            const appliedMessage = validHunks.length
                ? `Valid Hunks Applied: \n${validPatch}`
                : "";
            return `${invalidHunksMessage} \n ${appliedMessage}`;
        }
        patchAgent.tools.setFunction("patchFile", testPatchFile);
        const parsedAnswer = (0, diff_1.parsePatch)(patchData.patch);
        const fileName = parsedAnswer[0].oldFileName;
        await patchAgent.call(`Can you modify this file:
file path: ${fileName}
${patchData.before}

      so that it would look like this:
${patchData.after}?`);
        console.log({ successCount, attempts, total: dataset.length });
    }
}
async function saveToolDiagnosticFiles(patchData, patch, fixedPatch, validPatch, success) {
    const failureDir = success ? "success" : "fail";
    const patchHash = await (0, hashes_1.md5Hash)(patchData.patch);
    const dirName = `./src/dataset/diffs/test_files/${failureDir}/${patchHash}`;
    await (0, utils_1.mkdir)(dirName, { recursive: true });
    await (0, utils_1.writeFile)(`${dirName}/before.ignore.ts`, patchData.before);
    await (0, utils_1.writeFile)(`${dirName}/ai-patch.diff`, patch);
    await (0, utils_1.writeFile)(`${dirName}/actual-patch.diff`, patchData.patch);
    await (0, utils_1.writeFile)(`${dirName}/after.ignore.ts`, patchData.after);
    await (0, utils_1.writeFile)(`${dirName}/ai-fixed-patch.diff`, fixedPatch);
    await (0, utils_1.writeFile)(`${dirName}/ai-valid-patch.diff`, validPatch);
}
if (require.main === module) {
    testDataset();
}
//# sourceMappingURL=test.js.map