"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 SessionsService_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.SessionsService = 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");
const fs = require("fs/promises");
const path = require("path");
const session_dto_1 = require("./dto/session.dto");
const application_state_service_1 = require("../application-state/application-state.service");
const utils_1 = require("../utils");
const message_bus_service_1 = require("../message-bus/message-bus.service");
let SessionsService = SessionsService_1 = class SessionsService {
    constructor(sessionsRepository, projectsRepository, contextTemplatesRepository, systemPromptsRepository, applicationStateService, messageBusService, dataSource) {
        this.sessionsRepository = sessionsRepository;
        this.projectsRepository = projectsRepository;
        this.contextTemplatesRepository = contextTemplatesRepository;
        this.systemPromptsRepository = systemPromptsRepository;
        this.applicationStateService = applicationStateService;
        this.messageBusService = messageBusService;
        this.dataSource = dataSource;
        this.logger = new common_1.Logger(SessionsService_1.name);
    }
    async create(createSessionDto) {
        this.messageBusService.clear();
        const session = this.sessionsRepository.create({
            ...createSessionDto,
            status: session_dto_1.SessionStatus.ACTIVE,
        });
        if (!createSessionDto.model_id) {
            const recentModels = await this.applicationStateService.getRecentModels();
            if (recentModels.length > 0) {
                session.model_id = recentModels[0];
            }
        }
        if (createSessionDto.project_id) {
            const project = await this.projectsRepository.findOneBy({
                id: createSessionDto.project_id,
            });
            if (!project) {
                throw new common_1.NotFoundException(`Project with ID "${createSessionDto.project_id}" not found`);
            }
            session.project = project;
        }
        if (createSessionDto.system_prompt_id) {
            const systemPrompt = await this.systemPromptsRepository.findOneBy({
                id: createSessionDto.system_prompt_id,
            });
            if (!systemPrompt) {
                throw new common_1.NotFoundException(`SystemPrompt with ID "${createSessionDto.system_prompt_id}" not found`);
            }
            session.systemPrompt = systemPrompt;
        }
        else {
            const defaultSystemPrompt = await this.systemPromptsRepository.findOneBy({
                is_default: true,
            });
            if (defaultSystemPrompt) {
                session.systemPrompt = defaultSystemPrompt;
            }
        }
        if (createSessionDto.default_initial_context_template_id) {
            const template = await this.contextTemplatesRepository.findOneBy({
                id: createSessionDto.default_initial_context_template_id,
            });
            if (!template) {
                throw new common_1.NotFoundException(`ContextTemplate with ID "${createSessionDto.default_initial_context_template_id}" not found`);
            }
            session.defaultInitialContextTemplate = template;
        }
        else {
            const defaultInitial = await this.contextTemplatesRepository.findOneBy({
                is_default_initial: true,
            });
            if (defaultInitial) {
                session.defaultInitialContextTemplate = defaultInitial;
            }
        }
        if (createSessionDto.default_followup_context_template_id) {
            const template = await this.contextTemplatesRepository.findOneBy({
                id: createSessionDto.default_followup_context_template_id,
            });
            if (!template) {
                throw new common_1.NotFoundException(`ContextTemplate with ID "${createSessionDto.default_followup_context_template_id}" not found`);
            }
            session.defaultFollowupContextTemplate = template;
        }
        else {
            const defaultFollowup = await this.contextTemplatesRepository.findOneBy({
                is_default_followup: true,
            });
            if (defaultFollowup) {
                session.defaultFollowupContextTemplate = defaultFollowup;
            }
        }
        const savedSession = await this.sessionsRepository.save(session);
        await this.applicationStateService.setActiveSessionId(savedSession.id);
        return this.findOne(savedSession.id);
    }
    async findAll(filter, limit) {
        const query = this.sessionsRepository
            .createQueryBuilder('session')
            .leftJoinAndSelect('session.project', 'project')
            .leftJoinAndSelect('session.defaultInitialContextTemplate', 'defaultInitialContextTemplate')
            .leftJoinAndSelect('session.defaultFollowupContextTemplate', 'defaultFollowupContextTemplate')
            .leftJoinAndSelect('session.systemPrompt', 'systemPrompt')
            .leftJoinAndSelect('session.subAgent', 'subAgent')
            .leftJoinAndSelect('session.parentSession', 'parentSession')
            .addSelect((subQuery) => subQuery
            .select('COUNT(si.id)')
            .from(core_entities_1.SessionInput, 'si')
            .where('si.session_id = session.id'), 'sessionInputCount')
            .addSelect((subQuery) => subQuery
            .select("COALESCE(json_object('id', latest.id, 'user_prompt', CASE WHEN latest.user_prompt IS NULL THEN NULL ELSE CASE WHEN LENGTH(latest.user_prompt) > 200 THEN SUBSTR(latest.user_prompt, 1, 200) || '...' ELSE latest.user_prompt END END, 'role', latest.role, 'tool_calls', CASE WHEN latest.tool_calls IS NULL THEN NULL ELSE latest.tool_calls END, 'created_at', latest.created_at), 'null')")
            .from(core_entities_1.SessionInput, 'latest')
            .where('latest.session_id = session.id')
            .orderBy('latest.created_at', 'DESC')
            .limit(1), 'latestInput');
        if (filter === 'non-empty') {
            query.where('EXISTS (SELECT 1 FROM session_inputs si WHERE si.session_id = session.id)');
        }
        else if (filter === 'recent') {
            const effectiveLimit = Math.min(limit && limit > 0 ? limit : 10, 100);
            const sessionTable = this.sessionsRepository.metadata.tableName;
            query.where(`(session.is_running = 1 AND EXISTS (SELECT 1 FROM session_inputs si WHERE si.session_id = session.id) ` +
                `OR session.id IN (` +
                `SELECT sub.id FROM ${sessionTable} sub WHERE sub.is_running = 0 ` +
                `AND EXISTS (SELECT 1 FROM session_inputs si WHERE si.session_id = sub.id) ` +
                `ORDER BY sub.updated_at DESC LIMIT ${effectiveLimit}` +
                `))`);
            query.orderBy('session.is_running', 'DESC');
            query.addOrderBy('session.updated_at', 'DESC');
        }
        if (filter !== 'recent') {
            query.orderBy('session.created_at', 'DESC');
        }
        const result = await query.getRawAndEntities();
        return result.entities.map((session, index) => {
            const raw = result.raw[index];
            session.sessionInputCount = parseInt(raw.sessionInputCount, 10) || 0;
            if (raw.latestInput && raw.latestInput !== 'null') {
                try {
                    session.latestInput = JSON.parse(raw.latestInput);
                }
                catch {
                    session.latestInput = null;
                }
            }
            else {
                session.latestInput = null;
            }
            return session;
        });
    }
    async findOne(id, includeExecutionLogs = false) {
        const relations = [
            'project',
            'defaultInitialContextTemplate',
            'defaultFollowupContextTemplate',
            'systemPrompt',
            'sessionInputs',
            'sessionInputs.contextTemplate',
            'sessionInputs.aiActions',
            'subAgent',
            'parentSession',
        ];
        if (includeExecutionLogs) {
            relations.push('sessionInputs.aiActions.executionLogs');
        }
        const session = await this.sessionsRepository.findOne({
            where: { id },
            relations,
            order: {
                sessionInputs: {
                    sequence_number: 'ASC',
                    aiActions: {
                        order_of_execution: 'ASC',
                    },
                },
            },
        });
        if (!session) {
            throw new common_1.NotFoundException(`Session with ID "${id}" not found`);
        }
        return session;
    }
    async findOneLight(id) {
        const session = await this.sessionsRepository.findOne({
            where: { id },
            relations: [
                'project',
                'defaultInitialContextTemplate',
                'defaultFollowupContextTemplate',
                'systemPrompt',
                'subAgent',
                'parentSession',
            ],
        });
        if (!session) {
            throw new common_1.NotFoundException(`Session with ID "${id}" not found`);
        }
        return session;
    }
    async findActive() {
        const activeSessionId = await this.applicationStateService.getActiveSessionId();
        if (!activeSessionId) {
            return null;
        }
        try {
            return await this.findOneLight(activeSessionId);
        }
        catch (error) {
            if (error instanceof common_1.NotFoundException) {
                return null;
            }
            throw error;
        }
    }
    async findLatest() {
        return this.sessionsRepository.findOne({
            order: { created_at: 'DESC' },
        });
    }
    async setActive(id) {
        const exists = await this.sessionsRepository.existsBy({ id });
        if (!exists) {
            throw new common_1.NotFoundException(`Session with ID "${id}" not found`);
        }
        await this.applicationStateService.setActiveSessionId(id);
    }
    async update(id, updateSessionDto) {
        const session = await this.sessionsRepository.findOneBy({ id });
        if (!session) {
            throw new common_1.NotFoundException(`Session with ID "${id}" not found`);
        }
        if (updateSessionDto.model_id !== undefined) {
            session.model_id = updateSessionDto.model_id;
        }
        if (updateSessionDto.reasoning_effort !== undefined) {
            session.reasoning_effort = updateSessionDto.reasoning_effort;
        }
        if (updateSessionDto.session_title !== undefined) {
            session.session_title = updateSessionDto.session_title;
        }
        if (updateSessionDto.status !== undefined) {
            session.status = updateSessionDto.status;
            if ([
                session_dto_1.SessionStatus.COMPLETED,
                session_dto_1.SessionStatus.ABORTED,
                session_dto_1.SessionStatus.FAILED,
            ].includes(updateSessionDto.status)) {
                session.end_time = new Date();
            }
        }
        if (updateSessionDto.system_prompt_id !== undefined) {
            session.system_prompt_id = updateSessionDto.system_prompt_id;
        }
        if (updateSessionDto.default_initial_context_template_id !== undefined) {
            session.default_initial_context_template_id =
                updateSessionDto.default_initial_context_template_id;
        }
        if (updateSessionDto.default_followup_context_template_id !== undefined) {
            session.default_followup_context_template_id =
                updateSessionDto.default_followup_context_template_id;
        }
        if (updateSessionDto.url !== undefined) {
            session.url = updateSessionDto.url;
        }
        if (updateSessionDto.sub_agent_id !== undefined) {
            session.sub_agent_id = updateSessionDto.sub_agent_id;
        }
        if (updateSessionDto.parent_session_id !== undefined) {
            session.parent_session_id = updateSessionDto.parent_session_id;
        }
        if (updateSessionDto.is_running !== undefined) {
            session.is_running = updateSessionDto.is_running;
        }
        await this.sessionsRepository.save(session);
        return this.findOne(id);
    }
    async resetAllIsRunning() {
        await this.sessionsRepository.update({ is_running: true }, { is_running: false });
        this.logger.log('Reset is_running flag for all sessions to false.');
    }
    async remove(id) {
        const session = await this.findOne(id);
        const descendantIds = await this.findAllDescendantSessions(id);
        for (const descendantId of descendantIds.reverse()) {
            const descendant = await this.sessionsRepository.findOneBy({
                id: descendantId,
            });
            if (descendant) {
                await this.sessionsRepository.remove(descendant);
            }
        }
        await this.sessionsRepository.remove(session);
    }
    async findAllDescendantSessions(parentSessionId) {
        const children = await this.sessionsRepository.find({
            where: { parent_session_id: parentSessionId },
            select: ['id'],
        });
        const result = [];
        for (const child of children) {
            result.push(child.id);
            const descendants = await this.findAllDescendantSessions(child.id);
            result.push(...descendants);
        }
        return result;
    }
    async findChildSessions(parentSessionId) {
        return this.sessionsRepository.find({
            where: { parent_session_id: parentSessionId },
            relations: ['subAgent', 'sessionInputs', 'sessionInputs.contextTemplate'],
            order: { created_at: 'DESC' },
        });
    }
    async getFileChanges(sessionId) {
        const session = await this.findOne(sessionId);
        const projectRoot = process.env.REPOBURG_PROJECT_PATH || process.cwd();
        const fileActionTypes = [
            'create_file',
            'overwrite_file',
            'delete_file',
            'quick_edit',
            'patch',
            'apply_diff',
        ];
        const fileActionsMap = new Map();
        for (const input of session.sessionInputs || []) {
            for (const action of input.aiActions || []) {
                if (action.file_path &&
                    fileActionTypes.includes(action.action_type) &&
                    action.status !== 'execution_failed') {
                    const existing = fileActionsMap.get(action.file_path) || [];
                    existing.push(action);
                    fileActionsMap.set(action.file_path, existing);
                }
            }
        }
        const changes = [];
        for (const [filePath, actions] of fileActionsMap) {
            const sortedActions = actions.sort((a, b) => new Date(a.created_at).getTime() - new Date(b.created_at).getTime());
            const oldestAction = sortedActions[0];
            const initialContent = oldestAction.original_content_for_revert;
            let currentContent = null;
            try {
                const safePath = path.resolve(projectRoot, filePath);
                if (safePath.startsWith(projectRoot)) {
                    currentContent = await fs.readFile(safePath, 'utf8');
                }
            }
            catch {
                currentContent = null;
            }
            changes.push({
                file_path: filePath,
                initial_content: initialContent,
                current_content: currentContent,
            });
        }
        return changes.sort((a, b) => a.file_path.localeCompare(b.file_path));
    }
    async cloneSession(sourceSessionId) {
        const sourceSession = await this.findOne(sourceSessionId, true);
        const queryRunner = this.dataSource.createQueryRunner();
        await queryRunner.connect();
        await queryRunner.startTransaction();
        try {
            const newSession = queryRunner.manager.create(core_entities_1.Session, {
                project_id: sourceSession.project_id,
                session_title: sourceSession.session_title
                    ? `${sourceSession.session_title} (Copy)`
                    : 'Cloned Session',
                status: session_dto_1.SessionStatus.ACTIVE,
                system_prompt_id: sourceSession.system_prompt_id,
                default_initial_context_template_id: sourceSession.default_initial_context_template_id,
                default_followup_context_template_id: sourceSession.default_followup_context_template_id,
                model_id: sourceSession.model_id,
                reasoning_effort: sourceSession.reasoning_effort,
                url: sourceSession.url,
                sub_agent_id: sourceSession.sub_agent_id,
            });
            await queryRunner.manager.save(newSession);
            if (sourceSession.sessionInputs) {
                for (const sourceInput of sourceSession.sessionInputs) {
                    const newInput = queryRunner.manager.create(core_entities_1.SessionInput, {
                        session_id: newSession.id,
                        sequence_number: sourceInput.sequence_number,
                        user_prompt: sourceInput.user_prompt,
                        context_template_id: sourceInput.context_template_id,
                        ad_hoc_context_definition: sourceInput.ad_hoc_context_definition,
                        generated_context_string: sourceInput.generated_context_string,
                        execution_strategy: sourceInput.execution_strategy,
                        raw_llm_response: sourceInput.raw_llm_response,
                        llm_response_explanation: sourceInput.llm_response_explanation,
                        is_context_carrier: sourceInput.is_context_carrier,
                        thoughts: sourceInput.thoughts,
                        role: sourceInput.role,
                        input_token_count: sourceInput.input_token_count,
                        cached_token_count: sourceInput.cached_token_count,
                        output_token_count: sourceInput.output_token_count,
                        error_message: sourceInput.error_message,
                        tool_calls: sourceInput.tool_calls,
                    });
                    await queryRunner.manager.save(newInput);
                    if (sourceInput.aiActions) {
                        for (const sourceAction of sourceInput.aiActions) {
                            const newAction = queryRunner.manager.create(core_entities_1.AIAction, {
                                input_id: newInput.id,
                                action_type: sourceAction.action_type,
                                file_path: sourceAction.file_path,
                                content: sourceAction.content,
                                original_content_for_revert: sourceAction.original_content_for_revert,
                                command_string: sourceAction.command_string,
                                files: sourceAction.files,
                                folders: sourceAction.folders,
                                reason: sourceAction.reason,
                                handover_string: sourceAction.handover_string,
                                status: sourceAction.status,
                                order_of_execution: sourceAction.order_of_execution,
                                server_name: sourceAction.server_name,
                                tool_name: sourceAction.tool_name,
                                arguments: sourceAction.arguments,
                                plain: sourceAction.plain,
                                tool_call_id: sourceAction.tool_call_id,
                            });
                            await queryRunner.manager.save(newAction);
                            if (sourceAction.executionLogs) {
                                for (const sourceLog of sourceAction.executionLogs) {
                                    const newLog = queryRunner.manager.create(core_entities_1.ExecutionLog, {
                                        action_id: newAction.id,
                                        output: sourceLog.output,
                                        error_message: sourceLog.error_message,
                                    });
                                    await queryRunner.manager.save(newLog);
                                }
                            }
                        }
                    }
                }
            }
            await queryRunner.commitTransaction();
            return this.findOne(newSession.id, true);
        }
        catch (error) {
            await queryRunner.rollbackTransaction();
            throw error;
        }
        finally {
            await queryRunner.release();
        }
    }
    async revertFile(sessionId, filePath) {
        const session = await this.findOne(sessionId);
        const projectRoot = process.env.REPOBURG_PROJECT_PATH || process.cwd();
        const fileActionTypes = [
            'create_file',
            'overwrite_file',
            'delete_file',
            'quick_edit',
            'patch',
            'apply_diff',
        ];
        const fileActions = [];
        for (const input of session.sessionInputs || []) {
            for (const action of input.aiActions || []) {
                if (action.file_path === filePath &&
                    fileActionTypes.includes(action.action_type) &&
                    action.status !== 'execution_failed') {
                    fileActions.push(action);
                }
            }
        }
        if (fileActions.length === 0) {
            throw new common_1.NotFoundException(`No file actions found for path "${filePath}" in session ${sessionId}`);
        }
        const sortedActions = fileActions.sort((a, b) => new Date(a.created_at).getTime() - new Date(b.created_at).getTime());
        const oldestAction = sortedActions[0];
        const originalContent = oldestAction.original_content_for_revert;
        const safePath = path.resolve(projectRoot, filePath);
        if (!safePath.startsWith(projectRoot)) {
            throw new common_1.NotFoundException(`Path traversal detected: ${filePath}`);
        }
        try {
            if (originalContent === null) {
                await fs.unlink(safePath);
                this.logger.log(`Reverted created file by deleting: ${filePath}`);
            }
            else {
                await fs.mkdir(path.dirname(safePath), { recursive: true });
                await fs.writeFile(safePath, originalContent, 'utf8');
                this.logger.log(`Reverted file to original content: ${filePath}`);
            }
            for (const action of fileActions) {
                action.status = 'confirmed_reverted';
                await this.dataSource.manager.save(core_entities_1.AIAction, action);
            }
        }
        catch (error) {
            this.logger.error(`Failed to revert file ${filePath}: ${error.message}`);
            throw error;
        }
    }
    async getInputFileChanges(sessionId, inputIds) {
        const session = await this.findOne(sessionId);
        const sessionInputIds = (session.sessionInputs || []).map((i) => i.id);
        for (const inputId of inputIds) {
            if (!sessionInputIds.includes(inputId)) {
                throw new common_1.NotFoundException(`Input with ID "${inputId}" not found in session ${sessionId}`);
            }
        }
        const targetInputs = (session.sessionInputs || []).filter((i) => inputIds.includes(i.id));
        const fileActionTypes = [
            'create_file',
            'overwrite_file',
            'delete_file',
            'quick_edit',
            'patch',
            'apply_diff',
        ];
        const fileActionsMap = new Map();
        for (const input of targetInputs) {
            for (const action of input.aiActions || []) {
                if (action.file_path &&
                    fileActionTypes.includes(action.action_type) &&
                    action.status !== 'execution_failed') {
                    const existing = fileActionsMap.get(action.file_path) || [];
                    existing.push(action);
                    fileActionsMap.set(action.file_path, existing);
                }
            }
        }
        const changes = [];
        for (const [filePath, actions] of fileActionsMap) {
            const sortedActions = actions.sort((a, b) => new Date(a.created_at).getTime() - new Date(b.created_at).getTime());
            const oldestAction = sortedActions[0];
            const initialContent = oldestAction.original_content_for_revert;
            const newestAction = sortedActions[sortedActions.length - 1];
            const currentContent = newestAction.content;
            changes.push({
                file_path: filePath,
                initial_content: initialContent,
                current_content: currentContent,
            });
        }
        return changes.sort((a, b) => a.file_path.localeCompare(b.file_path));
    }
    async revertInputFileChanges(sessionId, inputIds) {
        const session = await this.findOne(sessionId);
        const projectRoot = process.env.REPOBURG_PROJECT_PATH || process.cwd();
        const sessionInputIds = (session.sessionInputs || []).map((i) => i.id);
        for (const inputId of inputIds) {
            if (!sessionInputIds.includes(inputId)) {
                throw new common_1.NotFoundException(`Input with ID "${inputId}" not found in session ${sessionId}`);
            }
        }
        const targetInputs = (session.sessionInputs || []).filter((i) => inputIds.includes(i.id));
        const fileActionTypes = [
            'create_file',
            'overwrite_file',
            'delete_file',
            'quick_edit',
            'patch',
            'apply_diff',
        ];
        const fileActionsMap = new Map();
        for (const input of targetInputs) {
            for (const action of input.aiActions || []) {
                if (action.file_path &&
                    fileActionTypes.includes(action.action_type) &&
                    action.status !== 'execution_failed') {
                    const existing = fileActionsMap.get(action.file_path) || [];
                    existing.push(action);
                    fileActionsMap.set(action.file_path, existing);
                }
            }
        }
        const result = {
            reverted: [],
            failed: [],
            errors: [],
        };
        const targetInputSequences = targetInputs.map((i) => i.sequence_number);
        const maxTargetSequence = Math.max(...targetInputSequences);
        const laterInputs = (session.sessionInputs || []).filter((i) => i.sequence_number > maxTargetSequence);
        const laterFilePaths = new Set();
        for (const input of laterInputs) {
            for (const action of input.aiActions || []) {
                if (action.file_path &&
                    fileActionTypes.includes(action.action_type) &&
                    action.status !== 'execution_failed') {
                    laterFilePaths.add(action.file_path);
                }
            }
        }
        for (const [filePath, actions] of fileActionsMap) {
            try {
                const sortedActions = actions.sort((a, b) => new Date(a.created_at).getTime() - new Date(b.created_at).getTime());
                const oldestAction = sortedActions[0];
                const originalContent = oldestAction.original_content_for_revert;
                const safePath = path.resolve(projectRoot, filePath);
                if (!safePath.startsWith(projectRoot)) {
                    result.failed.push(filePath);
                    result.errors.push(`Path traversal detected: ${filePath}`);
                    continue;
                }
                if (originalContent === null) {
                    await fs.unlink(safePath);
                    this.logger.log(`Reverted section-created file by deleting: ${filePath}`);
                }
                else {
                    await fs.mkdir(path.dirname(safePath), { recursive: true });
                    await fs.writeFile(safePath, originalContent, 'utf8');
                    this.logger.log(`Reverted file to section-start content: ${filePath}`);
                }
                for (const action of actions) {
                    action.status = 'confirmed_reverted';
                    await this.dataSource.manager.save(core_entities_1.AIAction, action);
                }
                result.reverted.push(filePath);
            }
            catch (error) {
                result.failed.push(filePath);
                result.errors.push(error.message);
            }
        }
        return result;
    }
    async revertSession(sessionId) {
        const changes = await this.getFileChanges(sessionId);
        const result = {
            reverted: [],
            failed: [],
            errors: [],
        };
        const createdFiles = changes.filter((c) => c.initial_content === null && c.current_content !== null);
        const otherFiles = changes.filter((c) => c.initial_content !== null || c.current_content === null);
        for (const change of createdFiles) {
            try {
                await this.revertFile(sessionId, change.file_path);
                result.reverted.push(change.file_path);
            }
            catch (error) {
                result.failed.push(change.file_path);
                result.errors.push(error.message);
            }
        }
        for (const change of otherFiles) {
            try {
                await this.revertFile(sessionId, change.file_path);
                result.reverted.push(change.file_path);
            }
            catch (error) {
                result.failed.push(change.file_path);
                result.errors.push(error.message);
            }
        }
        return result;
    }
};
exports.SessionsService = SessionsService;
__decorate([
    (0, utils_1.Trace)(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [session_dto_1.CreateSessionDto]),
    __metadata("design:returntype", Promise)
], SessionsService.prototype, "create", null);
__decorate([
    (0, utils_1.Trace)(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String, Number]),
    __metadata("design:returntype", Promise)
], SessionsService.prototype, "findAll", null);
__decorate([
    (0, utils_1.Trace)(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String, Object]),
    __metadata("design:returntype", Promise)
], SessionsService.prototype, "findOne", null);
__decorate([
    (0, utils_1.Trace)(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String]),
    __metadata("design:returntype", Promise)
], SessionsService.prototype, "findOneLight", null);
__decorate([
    (0, utils_1.Trace)(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", []),
    __metadata("design:returntype", Promise)
], SessionsService.prototype, "findActive", null);
__decorate([
    (0, utils_1.Trace)(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", []),
    __metadata("design:returntype", Promise)
], SessionsService.prototype, "findLatest", null);
__decorate([
    (0, utils_1.Trace)(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String]),
    __metadata("design:returntype", Promise)
], SessionsService.prototype, "setActive", null);
__decorate([
    (0, utils_1.Trace)(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String, session_dto_1.UpdateSessionDto]),
    __metadata("design:returntype", Promise)
], SessionsService.prototype, "update", null);
__decorate([
    (0, utils_1.Trace)(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String]),
    __metadata("design:returntype", Promise)
], SessionsService.prototype, "remove", null);
__decorate([
    (0, utils_1.Trace)(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String]),
    __metadata("design:returntype", Promise)
], SessionsService.prototype, "findChildSessions", null);
__decorate([
    (0, utils_1.Trace)(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String]),
    __metadata("design:returntype", Promise)
], SessionsService.prototype, "getFileChanges", null);
__decorate([
    (0, utils_1.Trace)(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String]),
    __metadata("design:returntype", Promise)
], SessionsService.prototype, "cloneSession", null);
__decorate([
    (0, utils_1.Trace)(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String, String]),
    __metadata("design:returntype", Promise)
], SessionsService.prototype, "revertFile", null);
__decorate([
    (0, utils_1.Trace)(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String, Array]),
    __metadata("design:returntype", Promise)
], SessionsService.prototype, "getInputFileChanges", null);
__decorate([
    (0, utils_1.Trace)(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String, Array]),
    __metadata("design:returntype", Promise)
], SessionsService.prototype, "revertInputFileChanges", null);
__decorate([
    (0, utils_1.Trace)(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String]),
    __metadata("design:returntype", Promise)
], SessionsService.prototype, "revertSession", null);
exports.SessionsService = SessionsService = SessionsService_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.Project)),
    __param(2, (0, typeorm_1.InjectRepository)(core_entities_1.ContextTemplate)),
    __param(3, (0, typeorm_1.InjectRepository)(core_entities_1.SystemPrompt)),
    __metadata("design:paramtypes", [typeorm_2.Repository,
        typeorm_2.Repository,
        typeorm_2.Repository,
        typeorm_2.Repository,
        application_state_service_1.ApplicationStateService,
        message_bus_service_1.MessageBusService,
        typeorm_2.DataSource])
], SessionsService);
//# sourceMappingURL=sessions.service.js.map