"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var DeleteFileHandler_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.DeleteFileHandler = void 0;
const common_1 = require("@nestjs/common");
const fs = require("fs/promises");
const path = require("path");
const class_transformer_1 = require("class-transformer");
const class_validator_1 = require("class-validator");
const delete_file_args_dto_1 = require("./dto/delete-file.args.dto");
const utils_1 = require("../../utils");
let DeleteFileHandler = DeleteFileHandler_1 = class DeleteFileHandler {
    constructor() {
        this.toolName = 'delete_file';
        this.logger = new common_1.Logger(DeleteFileHandler_1.name);
        this.projectRoot = process.env.REPOBURG_PROJECT_PATH || process.cwd();
    }
    getMetadata() {
        return {
            name: this.toolName,
            description: this.getDefinition(),
            arguments: [
                {
                    name: 'file_path',
                    type: 'string',
                    description: 'The relative path of file to delete.',
                    required: true,
                },
            ],
        };
    }
    generateExample(toolCall) {
        return (0, utils_1.generateToolCallJson)(toolCall);
    }
    getDefinition() {
        const example = this.generateExample({
            tool_name: this.toolName,
            file_path: 'src/legacy/old-api-client.js',
        });
        const definition = `
-------------
### ${this.toolName}
  Deletes a file from the filesystem.

  #### Parameters
  - "file_path": (string) The relative path of file to delete.

  #### Example
    Explanation: Remove the old, unused 'legacy.js' file.
:${example}
-------------
`;
        return `\n${definition.trim()}\n`;
    }
    resolveAndValidatePath(unsafePath) {
        const normalizedPath = path.normalize(unsafePath);
        if (path.isAbsolute(normalizedPath)) {
            throw new common_1.BadRequestException(`Absolute paths are not allowed: ${unsafePath}`);
        }
        const resolvedPath = path.resolve(this.projectRoot, normalizedPath);
        if (!resolvedPath.startsWith(this.projectRoot)) {
            throw new common_1.BadRequestException(`Path traversal is not allowed: ${unsafePath}`);
        }
        return resolvedPath;
    }
    async readFileContent(filePath) {
        try {
            return await fs.readFile(filePath, 'utf8');
        }
        catch (error) {
            if (error.code === 'ENOENT') {
                return null;
            }
            throw error;
        }
    }
    async execute(args, _context) {
        const validatedArgs = (0, class_transformer_1.plainToClass)(delete_file_args_dto_1.DeleteFileArgsDto, args);
        const errors = await (0, class_validator_1.validate)(validatedArgs);
        if (errors.length > 0) {
            const errorMessages = errors
                .map((err) => Object.values(err.constraints || {}).join(', '))
                .join('; ');
            return {
                status: 'FAILURE',
                summary: `Invalid arguments for ${this.toolName}.`,
                error_message: errorMessages,
                persisted_args: args,
                execution_log: { output: '', error_message: errorMessages },
            };
        }
        const { file_path } = validatedArgs;
        try {
            const safePath = this.resolveAndValidatePath(file_path);
            const originalContent = await this.readFileContent(safePath);
            await fs.unlink(safePath);
            return {
                status: 'SUCCESS',
                summary: `File "${file_path}" deleted.`,
                persisted_args: { file_path },
                original_content_for_revert: originalContent,
                execution_log: {
                    output: `${file_path} has been deleted.`,
                    error_message: '',
                },
            };
        }
        catch (error) {
            if (error.code === 'ENOENT') {
                return {
                    status: 'SUCCESS',
                    summary: `File "${file_path}" did not exist, considered deleted.`,
                    persisted_args: { file_path },
                    original_content_for_revert: null,
                    execution_log: {
                        output: `${file_path} did not exist.`,
                        error_message: '',
                    },
                };
            }
            this.logger.error(`Failed to delete file at ${file_path}: ${error.message}`);
            return {
                status: 'FAILURE',
                summary: `Failed to delete file "${file_path}": ${error.message}`,
                error_message: error.message,
                persisted_args: validatedArgs,
                execution_log: { output: '', error_message: error.message },
            };
        }
    }
};
exports.DeleteFileHandler = DeleteFileHandler;
exports.DeleteFileHandler = DeleteFileHandler = DeleteFileHandler_1 = __decorate([
    (0, common_1.Injectable)()
], DeleteFileHandler);
//# sourceMappingURL=delete-file.handler.js.map