"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.stringReplace = stringReplace;
const fs = __importStar(require("fs"));
const services_1 = require("../../services");
const utils_1 = require("../../utils");
async function stringReplace(findString, replaceString, filePaths) {
    const toolService = (this instanceof services_1.ToolsService ? this : (0, services_1.services)().Tools);
    const context = toolService.getContext();
    if (!findString ||
        replaceString === undefined ||
        !filePaths ||
        filePaths.length === 0) {
        throw new Error("findString, replaceString, and filePaths are all required parameters");
    }
    const results = [];
    let totalReplacements = 0;
    for (const filePath of filePaths) {
        try {
            const exists = await (0, utils_1.fileExists)(filePath);
            if (!exists) {
                results.push(`❌ File not found: ${filePath}`);
                continue;
            }
            const content = fs.readFileSync(filePath, "utf8");
            const originalContent = content;
            const matches = content.split(findString).length - 1;
            if (matches === 0) {
                results.push(`ℹ️  No matches found in: ${filePath}`);
                continue;
            }
            const eventResults = [];
            if (context.Events) {
                eventResults.push(...(await context.Events.emitBlocking("file:pre-edit", {
                    filePath,
                    operation: "stringReplace",
                    findString,
                    replaceString,
                    originalContent,
                })));
            }
            const newContent = content.replace(new RegExp(findString.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "g"), replaceString);
            fs.writeFileSync(filePath, newContent);
            totalReplacements += matches;
            results.push(`✅ Replaced ${matches} occurrence(s) in: ${filePath}`);
            if (context.Events) {
                eventResults.push(...(await context.Events.emitBlocking("file:post-edit", {
                    filePath,
                    operation: "stringReplace",
                    findString,
                    replaceString,
                    originalContent,
                    updatedContent: newContent,
                })));
            }
            if (eventResults && eventResults.length > 0) {
                const eventResultsText = eventResults
                    .filter((r) => r && typeof r === "string" && r.trim())
                    .join("\n");
                if (eventResultsText) {
                    results.push(eventResultsText);
                }
            }
        }
        catch (error) {
            results.push(`❌ Error processing ${filePath}: ${error.message}`);
        }
    }
    const summary = `\n📊 Summary: ${totalReplacements} total replacements made across ${filePaths.length} file(s)`;
    return results.join("\n") + summary;
}
//# sourceMappingURL=stringReplace.js.map