"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 CreateFileHandler_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.CreateFileHandler = 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 create_file_args_dto_1 = require("./dto/create-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 CreateFileHandler = CreateFileHandler_1 = class CreateFileHandler {
    constructor(syntaxValidator, appStateService) {
        this.syntaxValidator = syntaxValidator;
        this.appStateService = appStateService;
        this.toolName = 'create_file';
        this.logger = new common_1.Logger(CreateFileHandler_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 for the new file.',
                    required: true,
                },
                {
                    name: 'content',
                    type: 'string',
                    description: 'The full content of the new file.',
                    required: true,
                },
            ],
        };
    }
    generateExample(toolCall) {
        return (0, utils_1.generateToolCallJson)(toolCall);
    }
    getDefinition() {
        const exampleContent = `\`\`\`typescript
import { v4 as uuidv4 } from 'uuid';

export interface UserProfile {
  id: string;
  username: string;
  email: string;
  createdAt: Date;
}

/**
 * Creates a new user profile with a unique ID and creation date.
 * @param username The user's chosen username.
 * @param email The user's email address.
 * @returns A new UserProfile object.
 */
export function createProfile(username: string, email: string): UserProfile {
  return {
    id: uuidv4(),
    username,
    email,
    createdAt: new Date(),
  };
}
\`\`\``.trim();
        const example = this.generateExample({
            tool_name: this.toolName,
            file_path: 'src/modules/users/profiles.util.ts',
            content: exampleContent,
        });
        const definition = `
-------------
### ${this.toolName}
  Creates a new file with the specified content. It will create any necessary parent directories.

  #### Parameters
  - "file_path": (string) The relative path for the new file.
  - "content": (string) The full content of the new file.

  #### Example
    Explanation: Create a new utility file for creating user profiles.
:${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 execute(args, _context) {
        const validatedArgs = (0, class_transformer_1.plainToClass)(create_file_args_dto_1.CreateFileArgsDto, 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);
            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 newly created file "${file_path}"`);
                        let errorMessage = this.syntaxValidator.formatErrors(validationError);
                        errorMessage += `\n**CORRECTION:** The file content you provided contains syntax errors. `;
                        errorMessage += `Please review the errors above and fix the syntax issues. `;
                        errorMessage += `Common issues include: missing closing brackets/braces, unclosed strings, malformed imports, or invalid operators. `;
                        errorMessage += `Use \`create_file\` again with the corrected content.`;
                        await fs.unlink(safePath).catch(() => {
                        });
                        return {
                            status: 'FAILURE',
                            summary: `File "${file_path}" contains syntax errors and was not saved.`,
                            error_message: errorMessage,
                            persisted_args: validatedArgs,
                            execution_log: { output: '', error_message: errorMessage },
                        };
                    }
                }
            }
            return {
                status: 'SUCCESS',
                summary: `File "${file_path}" created.`,
                persisted_args: { file_path, content },
                execution_log: {
                    output: `${file_path} has been created.`,
                    error_message: '',
                },
            };
        }
        catch (error) {
            this.logger.error(`Failed to create file at ${file_path}: ${error.message}`);
            return {
                status: 'FAILURE',
                summary: `Failed to create file "${file_path}": ${error.message}`,
                error_message: error.message,
                persisted_args: validatedArgs,
                execution_log: { output: '', error_message: error.message },
            };
        }
    }
};
exports.CreateFileHandler = CreateFileHandler;
exports.CreateFileHandler = CreateFileHandler = CreateFileHandler_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])
], CreateFileHandler);
//# sourceMappingURL=create-file.handler.js.map