"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
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 __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
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 AiInteractionService_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.AiInteractionService = void 0;
const common_1 = require("@nestjs/common");
const core_1 = require("@nestjs/core");
const typeorm_1 = require("@nestjs/typeorm");
const typeorm_2 = require("typeorm");
const child_process_1 = require("child_process");
const fs = __importStar(require("fs/promises"));
const error_messages_1 = require("../constants/error-messages");
const ai_interaction_repository_1 = require("../repository/ai-interaction.repository");
const crud_service_1 = require("./crud.service");
const mcp_handler_factory_service_1 = require("./genai/mcp-handlers/mcp-handler-factory.service");
const publisher_factory_service_1 = require("./queues/publisher-factory.service");
let AiInteractionService = AiInteractionService_1 = class AiInteractionService extends crud_service_1.CRUDService {
    constructor(entityManager, repo, moduleRef, publisherFactory, mcpHandlerFactory) {
        super(entityManager, repo, 'aiInteraction', 'solid-core', moduleRef);
        this.entityManager = entityManager;
        this.repo = repo;
        this.moduleRef = moduleRef;
        this.publisherFactory = publisherFactory;
        this.mcpHandlerFactory = mcpHandlerFactory;
        this.logger = new common_1.Logger(AiInteractionService_1.name);
    }
    async triggerMcpClientJob(dto, userId, isAutoApply = false, threadId = null) {
        const aiInteraction = await this.create({
            userId: userId,
            threadId: threadId ? threadId : `thread-${userId}`,
            role: 'human',
            message: dto.prompt,
            contentType: '',
            errorMessage: '',
            modelUsed: '',
            responseTimeMs: 0,
            metadata: '',
            isAutoApply: isAutoApply
        });
        const m = {
            payload: {
                aiInteractionId: aiInteraction.id,
                moduleName: dto.moduleName
            },
            parentEntity: 'aiInteraction',
            parentEntityId: aiInteraction.id,
        };
        const queueMessageId = await this.publisherFactory.publish(m, 'TriggerMcpClientPublisher');
        return {
            queueMessageId: queueMessageId,
            aiInteractionId: aiInteraction.id
        };
    }
    async runMcpPrompt(prompt) {
        const pythonExecutable = this.settingService.getConfigValue('mcpPythonExecutable');
        const mcpClient = this.settingService.getConfigValue('mcpClient');
        if (!pythonExecutable || !mcpClient) {
            throw new common_1.BadRequestException(error_messages_1.ERROR_MESSAGES.PYTHON_EXECUTABLE_NOT_CONFIGURED);
        }
        try {
            const [pyStat, clientStat] = await Promise.all([
                fs.stat(pythonExecutable),
                fs.stat(mcpClient),
            ]);
            if (!pyStat.isFile()) {
                throw new common_1.BadRequestException(`MCP_PYTHON_EXECUTABLE path is not a file: ${pythonExecutable}`);
            }
            if (!clientStat.isFile()) {
                throw new common_1.BadRequestException(`MCP_CLIENT path is not a file: ${mcpClient}`);
            }
        }
        catch (err) {
            throw new common_1.BadRequestException(`Invalid MCP executable or client path: ${err.message}`);
        }
        return new Promise((resolve, reject) => {
            this.logger.log(`Attempting to run command:`);
            this.logger.log(`${pythonExecutable} ${mcpClient} "${prompt}"`);
            const python = (0, child_process_1.spawn)(pythonExecutable, [mcpClient, `"${prompt}"`]);
            let stdout = '';
            let stderr = '';
            python.stdout.on('data', (data) => {
                stdout += data.toString();
            });
            python.stderr.on('data', (data) => {
                stderr += data.toString();
            });
            python.on('close', (code) => {
                this.logger.log(`Python script exited with code ${code}`);
                if (code !== 0) {
                    this.logger.error(`Python script exited with a non-zero exit code: ${stderr}`);
                    return reject(new Error(`Python script exited with a non-zero exit code: ${stderr}`));
                }
                try {
                    this.logger.log(`Python script exited with zero exit code: ${stdout}`);
                    const raw = JSON.parse(stdout);
                    let parsedResponse = raw.response;
                    try {
                        parsedResponse = JSON.parse(raw.response);
                    }
                    catch (ex) {
                        this.logger.warn(`Attempting to parse mcp client response assuming it is JSON, however it is not: ${parsedResponse}`);
                    }
                    const enrichedRaw = {
                        ...raw,
                        response: parsedResponse,
                    };
                    resolve(enrichedRaw);
                }
                catch (err) {
                    reject(new Error(`Mcp Invocation Failed: ${err.message}`));
                }
            });
        });
    }
    cleanResponse(response) {
        this.logger.log(`mcp server response is: ${response}`);
        if (response.startsWith('```json')) {
            response = response.replace(/^```json/, '').trim();
        }
        if (response.endsWith('```')) {
            response = response.replace(/```$/, '').trim();
        }
        this.logger.log(`mcp server response after removing doc tags is: ${response}`);
        return response;
    }
    async applySolidAiInteraction(id) {
        const aiInteraction = await this.findOne(id, {
            populate: ['user']
        });
        if (!aiInteraction) {
            const m = `Unable to identified the aiInteraction entry that triggered this job... using id: ${id}`;
            throw new Error(m);
        }
        let metadata = {};
        try {
            if (typeof aiInteraction.metadata === "string") {
                metadata = JSON.parse(aiInteraction.metadata);
            }
            else if (typeof aiInteraction.metadata === "object" && aiInteraction.metadata !== null) {
                metadata = aiInteraction.metadata;
            }
            else {
                metadata = {};
            }
        }
        catch (e) {
            throw new Error(`Invalid metadata JSON: ${e}`);
        }
        const toolsInvoked = metadata['tools_invoked'];
        if (!toolsInvoked) {
            throw new Error(error_messages_1.ERROR_MESSAGES.UNABLE_TO_RESOLVE_SOLID_COMMAND);
        }
        const toolInvoked = toolsInvoked[0];
        const mcpToolHandler = this.mcpHandlerFactory.getInstance(toolInvoked);
        if (!mcpToolHandler) {
            throw new Error(error_messages_1.ERROR_MESSAGES.UNABLE_TO_RESOLVE_MCP_HANDLER);
        }
        const handlerApplicationResponse = await mcpToolHandler.apply(aiInteraction);
        await this.update(aiInteraction.id, { isApplied: true }, [], true);
        return handlerApplicationResponse;
    }
};
exports.AiInteractionService = AiInteractionService;
exports.AiInteractionService = AiInteractionService = AiInteractionService_1 = __decorate([
    (0, common_1.Injectable)(),
    __param(0, (0, typeorm_1.InjectEntityManager)()),
    __metadata("design:paramtypes", [typeorm_2.EntityManager,
        ai_interaction_repository_1.AiInteractionRepository,
        core_1.ModuleRef,
        publisher_factory_service_1.PublisherFactory,
        mcp_handler_factory_service_1.McpHandlerFactory])
], AiInteractionService);
//# sourceMappingURL=ai-interaction.service.js.map