"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 SessionTransferService_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.SessionTransferService = void 0;
const common_1 = require("@nestjs/common");
const typeorm_1 = require("@nestjs/typeorm");
const typeorm_2 = require("typeorm");
const core_entities_1 = require("../core-entities");
let SessionTransferService = SessionTransferService_1 = class SessionTransferService {
    constructor(sessionsRepository, sessionInputsRepository, aiActionsRepository, executionLogsRepository, systemPromptsRepository, dataSource) {
        this.sessionsRepository = sessionsRepository;
        this.sessionInputsRepository = sessionInputsRepository;
        this.aiActionsRepository = aiActionsRepository;
        this.executionLogsRepository = executionLogsRepository;
        this.systemPromptsRepository = systemPromptsRepository;
        this.dataSource = dataSource;
        this.logger = new common_1.Logger(SessionTransferService_1.name);
    }
    async exportSession(sessionId) {
        const session = await this.sessionsRepository.findOne({
            where: { id: sessionId },
            relations: ['systemPrompt'],
        });
        if (!session) {
            throw new common_1.NotFoundException(`Session with ID "${sessionId}" not found`);
        }
        const sessionInputs = await this.sessionInputsRepository.find({
            where: { session_id: sessionId },
            order: { sequence_number: 'ASC' },
        });
        const messages = [];
        if (session.systemPrompt) {
            messages.push({
                role: 'system',
                content: session.systemPrompt.prompt_content,
                system_prompt_id: session.system_prompt_id || undefined,
            });
        }
        for (const input of sessionInputs) {
            if (input.role === 'user' && input.generated_context_string) {
                messages.push({
                    role: 'user',
                    content: input.generated_context_string,
                    user_prompt: input.user_prompt || undefined,
                });
            }
            else if (input.role === 'model') {
                const msg = {
                    role: 'assistant',
                    content: input.raw_llm_response || '',
                };
                if (input.thoughts) {
                    msg.thoughts = input.thoughts;
                }
                if (input.tool_calls) {
                    try {
                        msg.tool_calls = JSON.parse(input.tool_calls);
                    }
                    catch (e) {
                        this.logger.warn(`Failed to parse tool_calls for input ${input.id}`);
                    }
                }
                messages.push(msg);
                if (msg.tool_calls && msg.tool_calls.length > 0) {
                    const toolActions = await this.aiActionsRepository.find({
                        where: { input_id: input.id },
                        relations: ['executionLogs'],
                    });
                    for (const action of toolActions) {
                        if (action.tool_call_id) {
                            const output = action.executionLogs?.[0]?.output || '';
                            const errorMessage = action.executionLogs?.[0]?.error_message || '';
                            let toolResult;
                            if (output && errorMessage) {
                                toolResult = `${output}\n\nError: ${errorMessage}`;
                            }
                            else if (errorMessage) {
                                toolResult = `Error: ${errorMessage}`;
                            }
                            else if (output) {
                                toolResult = output;
                            }
                            else {
                                continue;
                            }
                            messages.push({
                                role: 'tool',
                                tool_call_id: action.tool_call_id,
                                content: toolResult,
                            });
                        }
                    }
                }
            }
        }
        return {
            model: session.model_id,
            messages,
        };
    }
    async importSession(data) {
        const queryRunner = this.dataSource.createQueryRunner();
        await queryRunner.connect();
        await queryRunner.startTransaction();
        let messageCount = 0;
        try {
            const session = queryRunner.manager.create(core_entities_1.Session, {
                model_id: data.model || null,
                status: 'active',
            });
            await queryRunner.manager.save(session);
            let currentAssistantInputId = null;
            for (const msg of data.messages) {
                if (msg.role === 'system') {
                    let systemPromptId = null;
                    if (msg.system_prompt_id) {
                        const existing = await queryRunner.manager.findOneBy(core_entities_1.SystemPrompt, {
                            id: msg.system_prompt_id,
                        });
                        if (existing) {
                            systemPromptId = existing.id;
                        }
                    }
                    if (!systemPromptId) {
                        const defaultPrompt = await queryRunner.manager.findOneBy(core_entities_1.SystemPrompt, {
                            is_default: true,
                        });
                        systemPromptId = defaultPrompt?.id || null;
                    }
                    session.system_prompt_id = systemPromptId;
                    await queryRunner.manager.save(session);
                    messageCount++;
                }
                else if (msg.role === 'user') {
                    const input = queryRunner.manager.create(core_entities_1.SessionInput, {
                        session_id: session.id,
                        role: 'user',
                        generated_context_string: msg.content,
                        user_prompt: msg.user_prompt || null,
                    });
                    await queryRunner.manager.save(input);
                    messageCount++;
                }
                else if (msg.role === 'assistant') {
                    const input = queryRunner.manager.create(core_entities_1.SessionInput, {
                        session_id: session.id,
                        role: 'model',
                        raw_llm_response: msg.content,
                        thoughts: msg.thoughts || null,
                        tool_calls: msg.tool_calls ? JSON.stringify(msg.tool_calls) : null,
                    });
                    const savedInput = await queryRunner.manager.save(input);
                    currentAssistantInputId = savedInput.id;
                    messageCount++;
                }
                else if (msg.role === 'tool') {
                    if (!currentAssistantInputId) {
                        this.logger.warn('Tool message without preceding assistant message, skipping');
                        continue;
                    }
                    const action = queryRunner.manager.create(core_entities_1.AIAction, {
                        input_id: currentAssistantInputId,
                        action_type: 'tool',
                        status: 'completed',
                        tool_call_id: msg.tool_call_id || null,
                        order_of_execution: 0,
                    });
                    const savedAction = await queryRunner.manager.save(action);
                    const log = queryRunner.manager.create(core_entities_1.ExecutionLog, {
                        action_id: savedAction.id,
                        output: msg.content,
                    });
                    await queryRunner.manager.save(log);
                    messageCount++;
                }
            }
            await queryRunner.commitTransaction();
            this.logger.log(`Session imported successfully: ${session.id}`);
            return {
                message: 'Import successful',
                session_id: session.id,
                message_count: messageCount,
            };
        }
        catch (err) {
            await queryRunner.rollbackTransaction();
            this.logger.error(`Import failed: ${err.message}`, err.stack);
            throw new common_1.BadRequestException(`Import failed: ${err.message}`);
        }
        finally {
            await queryRunner.release();
        }
    }
};
exports.SessionTransferService = SessionTransferService;
exports.SessionTransferService = SessionTransferService = SessionTransferService_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.AIAction)),
    __param(3, (0, typeorm_1.InjectRepository)(core_entities_1.ExecutionLog)),
    __param(4, (0, typeorm_1.InjectRepository)(core_entities_1.SystemPrompt)),
    __metadata("design:paramtypes", [typeorm_2.Repository,
        typeorm_2.Repository,
        typeorm_2.Repository,
        typeorm_2.Repository,
        typeorm_2.Repository,
        typeorm_2.DataSource])
], SessionTransferService);
//# sourceMappingURL=session-transfer.service.js.map