"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 __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var OverwriteFileHandler_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.OverwriteFileHandler = 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 overwrite_file_args_dto_1 = require("./dto/overwrite-file.args.dto");
const utils_1 = require("../../utils");
const syntax_validation_service_1 = require("../../syntax-validation/syntax-validation.service");
const application_state_service_1 = require("../../application-state/application-state.service");
let OverwriteFileHandler = OverwriteFileHandler_1 = class OverwriteFileHandler {
    constructor(syntaxValidator, appStateService) {
        this.syntaxValidator = syntaxValidator;
        this.appStateService = appStateService;
        this.toolName = 'overwrite_file';
        this.logger = new common_1.Logger(OverwriteFileHandler_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 to the file to be overwritten.',
                    required: true,
                },
                {
                    name: 'content',
                    type: 'string',
                    description: 'The new, complete content for the file.',
                    required: true,
                },
            ],
        };
    }
    generateExample(toolCall) {
        return (0, utils_1.generateToolCallJson)(toolCall);
    }
    getDefinition() {
        const exampleContent = `\`\`\`typescript
/**
 * Global application configuration.
 */
export const AppConfig = Object.freeze({
  // Feature flags
  ENABLE_ANALYTICS: process.env.NODE_ENV === 'production',
  ENABLE_FEATURE_X: true,

  // API endpoints
  API_BASE_URL: process.env.API_URL || 'https://api.example.com',
  API_TIMEOUT: parseInt(process.env.API_TIMEOUT || '5000', 10),

  // Third-party service keys
  SENTRY_DSN: process.env.SENTRY_DSN,
});
\`\`\``.trim();
        const example = this.generateExample({
            tool_name: this.toolName,
            file_path: 'src/config/app.config.ts',
            content: exampleContent,
        });
        const badExampleContent = `\`\`\`typescript
  // This is wrong! Only a partial snippet is provided.
  NEW_API_KEY: 'ABC-123',
\`\`\``.trim();
        const badExample = this.generateExample({
            tool_name: this.toolName,
            file_path: 'src/config/app.config.ts',
            content: badExampleContent,
        });
        const definition = `
-------------
### ${this.toolName}
  Overwrites an existing file with new content. This is a destructive operation that replaces the **entire file**.
  You MUST provide the full, final content of the file. NEVER EVER provide only a snippet or partial content, as that will result in loss of data.

  #### Parameters
  - "file_path": (string) The relative path to the file to be overwritten.
  - "content": (string) The new, complete content for the file.

  #### Example
    Explanation: Refactor the entire 'app.config.ts' to a new, more structured format.
:${example}

  #### Bad Example
    Explanation: This is an incorrect use case. The 'content' field only contains a small snippet, not the entire file. This tool would wipe the original file and replace it with only the new lines, which is not the intended outcome.
:${badExample}
-------------
`;
        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)(overwrite_file_args_dto_1.OverwriteFileArgsDto, 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, content } = validatedArgs;
        try {
            const safePath = this.resolveAndValidatePath(file_path);
            const originalContent = await this.readFileContent(safePath);
            await fs.mkdir(path.dirname(safePath), { recursive: true });
            await fs.writeFile(safePath, content, 'utf8');
            if (this.syntaxValidator && this.appStateService) {
                const isValidationEnabled = await this.appStateService.getSyntaxValidationEnabled();
                if (isValidationEnabled) {
                    const validationError = await this.syntaxValidator.validate(file_path, content);
                    if (validationError) {
                        this.logger.warn(`Syntax validation failed for overwritten file "${file_path}"`);
                        let errorMessage = this.syntaxValidator.formatErrors(validationError);
                        errorMessage += `\n**CORRECTION:** Your overwrite introduced syntax errors. The original file content has been restored. `;
                        errorMessage += `Use \`overwrite_file\` again with the complete, corrected content. `;
                        errorMessage += `Remember: \`overwrite_file\` replaces the ENTIRE file - provide the full final content, not just the changed portion.`;
                        if (originalContent !== null) {
                            await fs.writeFile(safePath, originalContent, 'utf8');
                        }
                        else {
                            await fs.unlink(safePath).catch(() => { });
                        }
                        return {
                            status: 'FAILURE',
                            summary: `File "${file_path}" contains syntax errors and was reverted.`,
                            error_message: errorMessage,
                            persisted_args: validatedArgs,
                            execution_log: { output: '', error_message: errorMessage },
                            original_content_for_revert: originalContent,
                        };
                    }
                }
            }
            return {
                status: 'SUCCESS',
                summary: `File "${file_path}" overwritten.`,
                persisted_args: { file_path, content },
                original_content_for_revert: originalContent,
                execution_log: {
                    output: `${file_path} has been overwritten.`,
                    error_message: '',
                },
            };
        }
        catch (error) {
            this.logger.error(`Failed to overwrite file at ${file_path}: ${error.message}`);
            return {
                status: 'FAILURE',
                summary: `Failed to overwrite file "${file_path}": ${error.message}`,
                error_message: error.message,
                persisted_args: validatedArgs,
                execution_log: { output: '', error_message: error.message },
            };
        }
    }
};
exports.OverwriteFileHandler = OverwriteFileHandler;
exports.OverwriteFileHandler = OverwriteFileHandler = OverwriteFileHandler_1 = __decorate([
    (0, common_1.Injectable)(),
    __param(0, (0, common_1.Optional)()),
    __param(1, (0, common_1.Optional)()),
    __metadata("design:paramtypes", [syntax_validation_service_1.SyntaxValidationService,
        application_state_service_1.ApplicationStateService])
], OverwriteFileHandler);
//# sourceMappingURL=overwrite-file.handler.js.map