"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 GetSessionHistoryHandler_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.GetSessionHistoryHandler = void 0;
const common_1 = require("@nestjs/common");
const typeorm_1 = require("@nestjs/typeorm");
const typeorm_2 = require("typeorm");
const class_transformer_1 = require("class-transformer");
const class_validator_1 = require("class-validator");
const core_entities_1 = require("../../core-entities");
const get_session_history_args_dto_1 = require("./dto/get-session-history.args.dto");
let GetSessionHistoryHandler = GetSessionHistoryHandler_1 = class GetSessionHistoryHandler {
    constructor(sessionsRepository, sessionInputsRepository, systemPromptsRepository) {
        this.sessionsRepository = sessionsRepository;
        this.sessionInputsRepository = sessionInputsRepository;
        this.systemPromptsRepository = systemPromptsRepository;
        this.toolName = 'get_session_history';
        this.logger = new common_1.Logger(GetSessionHistoryHandler_1.name);
    }
    getMetadata() {
        return {
            name: this.toolName,
            description: 'Returns session history in JSON format, using the same structure sent to the AI (LlmContent format)',
            arguments: [
                {
                    name: 'session_id',
                    type: 'string',
                    description: 'Optional session ID. If not provided, uses the current session from context.',
                    required: false,
                },
                {
                    name: 'limit',
                    type: 'number',
                    description: 'Maximum number of conversation turns to return. If not provided, returns all turns.',
                    required: false,
                },
                {
                    name: 'include_system_prompt',
                    type: 'boolean',
                    description: 'Whether to include the system prompt in the returned history. Default: false',
                    required: false,
                },
            ],
        };
    }
    getDefinition() {
        return `## get_session_history

Returns the session history in JSON format, using the same structure that is sent to the AI (LlmContent format).

### Parameters:
- \`session_id\` (string, optional): Session ID. If not provided, uses the current session.
- \`limit\` (number, optional): Maximum number of conversation turns to return.
- \`include_system_prompt\` (boolean, optional): Whether to include the system prompt. Default: false.

### Returns:
JSON array of conversation turns with the following structure:
\`\`\`json
[
  {
    "role": "system" | "user" | "model",
    "content": "text content" | [{ "text": "content" }],
    "tool_calls": [...],
    "thoughts": "reasoning content"
  }
]
\`\`\`

### Example:
\`\`\`typescript
tool: get_session_history
args: {
  "session_id": "session-123",
  "limit": 10,
  "include_system_prompt": false
}
\`\`\``;
    }
    async execute(args, context) {
        try {
            const validatedArgs = (0, class_transformer_1.plainToClass)(get_session_history_args_dto_1.GetSessionHistoryArgsDto, args);
            const validationErrors = await (0, class_validator_1.validate)(validatedArgs);
            if (validationErrors.length > 0) {
                const errorMessages = validationErrors
                    .map((err) => Object.values(err.constraints || {}).join(', '))
                    .join('; ');
                throw new Error(`Validation error: ${errorMessages}`);
            }
            const { session_id, limit, include_system_prompt } = validatedArgs;
            let targetSessionId;
            if (session_id) {
                targetSessionId = session_id;
            }
            else {
                const currentSession = await this.sessionsRepository.findOne({
                    where: { id: context.session_id },
                    select: ['id', 'parent_session_id'],
                });
                if (!currentSession) {
                    throw new common_1.NotFoundException(`Current session "${context.session_id}" not found`);
                }
                targetSessionId = currentSession.parent_session_id || currentSession.id;
            }
            const session = await this.sessionsRepository.findOne({
                where: { id: targetSessionId },
                relations: ['systemPrompt'],
            });
            if (!session) {
                throw new common_1.NotFoundException(`Session with ID "${targetSessionId}" not found`);
            }
            const sessionInputs = await this.sessionInputsRepository.find({
                where: { session: { id: targetSessionId } },
                order: { created_at: 'ASC' },
            });
            const limitedInputs = limit ? sessionInputs.slice(-limit) : sessionInputs;
            const history = [];
            if (include_system_prompt && session.systemPrompt) {
                history.push({
                    role: 'system',
                    content: session.systemPrompt.prompt_content,
                });
            }
            for (const input of limitedInputs) {
                if (input.generated_context_string) {
                    history.push({
                        role: 'user',
                        content: input.generated_context_string,
                    });
                    if (input.raw_llm_response || input.tool_calls || input.thoughts) {
                        const modelTurn = {
                            role: 'model',
                            parts: [{ text: input.raw_llm_response || '' }],
                        };
                        if (input.tool_calls) {
                            try {
                                modelTurn.tool_calls = JSON.parse(input.tool_calls);
                            }
                            catch (e) {
                                this.logger.warn(`Failed to parse tool_calls for input ${input.id}: ${e.message}`);
                            }
                        }
                        if (input.thoughts) {
                            modelTurn.thoughts = input.thoughts;
                        }
                        history.push(modelTurn);
                    }
                }
            }
            const jsonOutput = JSON.stringify(history, null, 2);
            return {
                status: 'SUCCESS',
                summary: `Retrieved session history for "${targetSessionId}" with ${history.length} turn(s).\n\n\`\`\`json\n${jsonOutput}\n\`\`\``,
                execution_log: {
                    output: jsonOutput,
                },
                persisted_args: { session_id: targetSessionId, limit },
            };
        }
        catch (error) {
            this.logger.error(`Failed to get session history: ${error.message}`);
            return {
                status: 'FAILURE',
                summary: 'Failed to retrieve session history',
                error_message: error.message,
                execution_log: {
                    output: '',
                    error_message: error.message,
                },
            };
        }
    }
};
exports.GetSessionHistoryHandler = GetSessionHistoryHandler;
exports.GetSessionHistoryHandler = GetSessionHistoryHandler = GetSessionHistoryHandler_1 = __decorate([
    (0, common_1.Injectable)(),
    __param(0, (0, typeorm_1.InjectRepository)(core_entities_1.Session)),
    __param(1, (0, typeorm_1.InjectRepository)(core_entities_1.SessionInput)),
    __param(2, (0, typeorm_1.InjectRepository)(core_entities_1.SystemPrompt)),
    __metadata("design:paramtypes", [typeorm_2.Repository,
        typeorm_2.Repository,
        typeorm_2.Repository])
], GetSessionHistoryHandler);
//# sourceMappingURL=get-session-history.handler.js.map