"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); }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.McpChatController = void 0;
const api_1 = require("@hed-hog/api");
const api_locale_1 = require("@hed-hog/api-locale");
const common_1 = require("@nestjs/common");
const delete_dto_1 = require("../dto/delete.dto");
const create_conversation_dto_1 = require("./dto/create-conversation.dto");
const send_message_dto_1 = require("./dto/send-message.dto");
const mcp_chat_service_1 = require("./mcp-chat.service");
let McpChatController = class McpChatController {
    constructor(service) {
        this.service = service;
    }
    listConversations({ id }) {
        return this.service.listConversations(id);
    }
    createConversation({ id }, dto) {
        return this.service.createConversation(id, dto);
    }
    deleteConversations({ id }, dto) {
        return this.service.deleteConversations(id, dto.ids);
    }
    getMessages({ id }, conversationId) {
        return this.service.getMessages(conversationId, id);
    }
    sendMessage({ id }, conversationId, dto, locale) {
        return this.service.sendMessage(conversationId, id, locale, dto.message);
    }
    async sendMessageStream({ id }, conversationId, dto, locale, res) {
        var _a;
        res.setHeader('Content-Type', 'text/event-stream; charset=utf-8');
        res.setHeader('Cache-Control', 'no-cache, no-transform');
        res.setHeader('Connection', 'keep-alive');
        res.setHeader('X-Accel-Buffering', 'no');
        res.flushHeaders();
        const writeEvent = (payload) => {
            res.write(`data: ${JSON.stringify(payload)}\n\n`);
        };
        try {
            const messages = await this.service.sendMessage(conversationId, id, locale, dto.message);
            const lastAssistant = [...messages]
                .reverse()
                .find((msg) => msg.role === 'assistant');
            const content = (_a = lastAssistant === null || lastAssistant === void 0 ? void 0 : lastAssistant.content) !== null && _a !== void 0 ? _a : '';
            if (content.length > 0) {
                const chunkSize = Math.max(8, Math.min(32, Math.ceil(content.length / 80)));
                for (let cursor = 0; cursor < content.length; cursor += chunkSize) {
                    writeEvent({
                        type: 'chunk',
                        content: content.slice(cursor, cursor + chunkSize),
                    });
                }
            }
            writeEvent({ type: 'done', messages });
        }
        catch (error) {
            const message = error instanceof Error ? error.message : 'Failed to stream message';
            writeEvent({ type: 'error', message });
        }
        finally {
            res.end();
        }
    }
};
exports.McpChatController = McpChatController;
__decorate([
    (0, common_1.Get)(),
    __param(0, (0, api_1.User)()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", void 0)
], McpChatController.prototype, "listConversations", null);
__decorate([
    (0, common_1.Post)(),
    __param(0, (0, api_1.User)()),
    __param(1, (0, common_1.Body)()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, create_conversation_dto_1.CreateConversationDTO]),
    __metadata("design:returntype", void 0)
], McpChatController.prototype, "createConversation", null);
__decorate([
    (0, common_1.Delete)(),
    __param(0, (0, api_1.User)()),
    __param(1, (0, common_1.Body)()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, delete_dto_1.DeleteDTO]),
    __metadata("design:returntype", void 0)
], McpChatController.prototype, "deleteConversations", null);
__decorate([
    (0, common_1.Get)(':id/messages'),
    __param(0, (0, api_1.User)()),
    __param(1, (0, common_1.Param)('id', common_1.ParseIntPipe)),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, Number]),
    __metadata("design:returntype", void 0)
], McpChatController.prototype, "getMessages", null);
__decorate([
    (0, common_1.Post)(':id/messages'),
    __param(0, (0, api_1.User)()),
    __param(1, (0, common_1.Param)('id', common_1.ParseIntPipe)),
    __param(2, (0, common_1.Body)()),
    __param(3, (0, api_locale_1.Locale)()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, Number, send_message_dto_1.SendMessageDTO, String]),
    __metadata("design:returntype", void 0)
], McpChatController.prototype, "sendMessage", null);
__decorate([
    (0, common_1.Post)(':id/messages/stream'),
    __param(0, (0, api_1.User)()),
    __param(1, (0, common_1.Param)('id', common_1.ParseIntPipe)),
    __param(2, (0, common_1.Body)()),
    __param(3, (0, api_locale_1.Locale)()),
    __param(4, (0, common_1.Res)()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, Number, send_message_dto_1.SendMessageDTO, String, Object]),
    __metadata("design:returntype", Promise)
], McpChatController.prototype, "sendMessageStream", null);
exports.McpChatController = McpChatController = __decorate([
    (0, api_1.Role)(),
    (0, common_1.Controller)('mcp-chat'),
    __metadata("design:paramtypes", [mcp_chat_service_1.McpChatService])
], McpChatController);
//# sourceMappingURL=mcp-chat.controller.js.map