"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 WriteTodoHandler_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.WriteTodoHandler = 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 write_todo_args_dto_1 = require("./dto/write-todo.args.dto");
const utils_1 = require("../../utils");
let WriteTodoHandler = WriteTodoHandler_1 = class WriteTodoHandler {
    constructor() {
        this.toolName = 'write_todo';
        this.logger = new common_1.Logger(WriteTodoHandler_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 todo file (e.g., ".repoburg/tasks/feature-x.md").',
                    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 = `\`\`markdown
:# Project TODOs

:- [x] Setup project structure
:- [ ] Implement login feature
  - [ ] Create login form component
  - [ ] Integrate with auth API
:- [ ] Write documentation
\`\``.trim();
        const example = this.generateExample({
            tool_name: this.toolName,
            file_path: '.repoburg/tasks/project-setup.md',
            content: exampleContent,
        });
        const definition = `
-------------### ${this.toolName}
  The **all-in-one tool** for managing TODOs and task lists.
  Use this tool for ANY task-related operation: creating new lists, **updating progress** (checking off items), adding new tasks, or modifying existing ones.
  Technically, it works exactly like \`overwrite_file\` (overwriting **entire file**), but it acts as a clear semantic signal that you are managing project tasks.
  **Rules for File Path:**
  - All task files MUST be placed in \`.repoburg/tasks/\` directory.
  - The filename should be meaningful and relevant to the current task (e.g., \`auth-refactor.md\`, \`bug-fix-123.md\`).

  #### Parameters
  - "file_path": (string) The relative path to the todo file (e.g., ".repoburg/tasks/feature-x.md").
  - "content": (string) The new, complete content for the file.

  #### Example
    Explanation: Update the project's TODO list to mark setup as done.
:${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)(write_todo_args_dto_1.WriteTodoArgsDto, 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');
            return {
                status: 'SUCCESS',
                summary: `TODO file "${file_path}" updated.`,
                persisted_args: { file_path, content },
                original_content_for_revert: originalContent,
                execution_log: {
                    output: `${file_path} has been updated.`,
                    error_message: '',
                },
            };
        }
        catch (error) {
            this.logger.error(`Failed to write todo file at ${file_path}: ${error.message}`);
            return {
                status: 'FAILURE',
                summary: `Failed to write todo file "${file_path}": ${error.message}`,
                error_message: error.message,
                persisted_args: validatedArgs,
                execution_log: { output: '', error_message: error.message },
            };
        }
    }
};
exports.WriteTodoHandler = WriteTodoHandler;
exports.WriteTodoHandler = WriteTodoHandler = WriteTodoHandler_1 = __decorate([
    (0, common_1.Injectable)()
], WriteTodoHandler);
//# sourceMappingURL=write-todo.handler.js.map