"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 LlmResponsesService_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.LlmResponsesService = void 0;
const common_1 = require("@nestjs/common");
const sessions_service_1 = require("../sessions/sessions.service");
const application_state_service_1 = require("../application-state/application-state.service");
const session_inputs_service_1 = require("../session-inputs/session-inputs.service");
const core_entities_1 = require("../core-entities");
const typeorm_1 = require("@nestjs/typeorm");
const typeorm_2 = require("typeorm");
const events_gateway_1 = require("../events/events.gateway");
const parsing_constants_1 = require("../llm-orchestration/parser/parsing.constants");
const chat_service_1 = require("../interactive-chat/chat.service");
const system_prompts_service_1 = require("../system-prompts/system-prompts.service");
const llm_turn_processor_service_1 = require("../llm-orchestration/llm-turn-processor.service");
let LlmResponsesService = LlmResponsesService_1 = class LlmResponsesService {
    constructor(sessionsRepository, sessionInputsRepository, systemPromptsService, sessionsService, applicationStateService, sessionInputsService, eventsGateway, chatService, newTurnProcessor) {
        this.sessionsRepository = sessionsRepository;
        this.sessionInputsRepository = sessionInputsRepository;
        this.systemPromptsService = systemPromptsService;
        this.sessionsService = sessionsService;
        this.applicationStateService = applicationStateService;
        this.sessionInputsService = sessionInputsService;
        this.eventsGateway = eventsGateway;
        this.chatService = chatService;
        this.newTurnProcessor = newTurnProcessor;
        this.logger = new common_1.Logger(LlmResponsesService_1.name);
    }
    async createPendingAiInput(sessionId, executionStrategy) {
        this.logger.log(`Creating pending AI input for session ${sessionId}`);
        const newSessionInput = this.sessionInputsRepository.create({
            session: { id: sessionId },
            role: 'model',
            execution_strategy: executionStrategy,
            raw_llm_response: null,
        });
        return this.sessionInputsRepository.save(newSessionInput);
    }
    async updatePendingAiInputWithError(pendingInputId, errorMessage) {
        this.logger.log(`Marking input ${pendingInputId} as failed: ${errorMessage}`);
        const sessionInput = await this.sessionInputsRepository.findOneBy({
            id: pendingInputId,
        });
        if (!sessionInput) {
            throw new common_1.NotFoundException(`Pending SessionInput with ID "${pendingInputId}" not found.`);
        }
        sessionInput.error_message = errorMessage;
        return this.sessionInputsRepository.save(sessionInput);
    }
    async finalizePendingAiInput(pendingInputId, dto) {
        const { raw_llm_response, input_token_count, output_token_count, cached_token_count, tool_calls, thoughts, } = dto;
        const sessionInput = await this.sessionInputsRepository.findOneBy({
            id: pendingInputId,
        });
        if (!sessionInput) {
            throw new common_1.NotFoundException(`Pending SessionInput with ID "${pendingInputId}" not found for finalization.`);
        }
        if (input_token_count !== undefined) {
            sessionInput.input_token_count = input_token_count;
        }
        if (output_token_count !== undefined) {
            sessionInput.output_token_count = output_token_count;
        }
        if (cached_token_count !== undefined) {
            sessionInput.cached_token_count = cached_token_count;
        }
        if (tool_calls && tool_calls.length > 0) {
            sessionInput.tool_calls = JSON.stringify(tool_calls);
        }
        if (thoughts) {
            sessionInput.thoughts = thoughts;
        }
        const cleanedLlmResponse = await this.extractAndUpdateSessionTitle(sessionInput.session_id, raw_llm_response);
        sessionInput.raw_llm_response = cleanedLlmResponse;
        const updatedSessionInput = await this.sessionInputsRepository.save(sessionInput);
        this.logger.log(`Finalized input ${updatedSessionInput.id}, routing to orchestration.`);
        this.eventsGateway.sendToAll('refresh-ui', {
            sessionId: updatedSessionInput.session_id,
        });
        return this.newTurnProcessor.processTurn(updatedSessionInput);
    }
    async extractAndUpdateSessionTitle(sessionId, rawResponse) {
        const startIndex = rawResponse.indexOf(parsing_constants_1.TITLE_START_TAG);
        const endIndex = rawResponse.indexOf(parsing_constants_1.TITLE_END_TAG);
        if (startIndex !== -1 && endIndex !== -1 && endIndex > startIndex) {
            const title = rawResponse
                .substring(startIndex + parsing_constants_1.TITLE_START_TAG.length, endIndex)
                .trim();
            if (title) {
                this.logger.log(`Extracted session title: "${title}" for session ID ${sessionId}`);
                await this.sessionsService.update(sessionId, { session_title: title });
            }
            const cleanedResponse = rawResponse.substring(0, startIndex) +
                rawResponse.substring(endIndex + parsing_constants_1.TITLE_END_TAG.length);
            return cleanedResponse.trim();
        }
        return rawResponse;
    }
    async submit(dto) {
        const { inputId, raw_llm_response, input_token_count, output_token_count, cached_token_count, tool_calls, } = dto;
        if (!inputId) {
            throw new Error('inputId is required for LLM response submission.');
        }
        this.logger.log(`Processing LLM response for existing input ${inputId}`);
        const sessionInput = await this.sessionInputsRepository.findOneBy({
            id: inputId,
        });
        if (!sessionInput) {
            throw new common_1.NotFoundException(`SessionInput with ID "${inputId}" not found.`);
        }
        if (!sessionInput.execution_strategy && dto.execution_strategy) {
            sessionInput.execution_strategy = dto.execution_strategy;
        }
        if (input_token_count !== undefined) {
            sessionInput.input_token_count = input_token_count;
        }
        if (output_token_count !== undefined) {
            sessionInput.output_token_count = output_token_count;
        }
        if (cached_token_count !== undefined) {
            sessionInput.cached_token_count = cached_token_count;
        }
        if (tool_calls && tool_calls.length > 0) {
            sessionInput.tool_calls = JSON.stringify(tool_calls);
        }
        const cleanedLlmResponse = await this.extractAndUpdateSessionTitle(sessionInput.session_id, raw_llm_response);
        sessionInput.raw_llm_response = cleanedLlmResponse;
        const updatedSessionInput = await this.sessionInputsRepository.save(sessionInput);
        this.logger.log(`Routing input ${updatedSessionInput.id} to orchestration flow.`);
        const result = await this.newTurnProcessor.processTurn(updatedSessionInput);
        this.eventsGateway.sendToAll('refresh-ui', {
            sessionId: updatedSessionInput.session_id,
        });
        return result;
    }
};
exports.LlmResponsesService = LlmResponsesService;
exports.LlmResponsesService = LlmResponsesService = LlmResponsesService_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(5, (0, common_1.Inject)((0, common_1.forwardRef)(() => session_inputs_service_1.SessionInputsService))),
    __param(7, (0, common_1.Inject)((0, common_1.forwardRef)(() => chat_service_1.ChatService))),
    __metadata("design:paramtypes", [typeorm_2.Repository,
        typeorm_2.Repository,
        system_prompts_service_1.SystemPromptsService,
        sessions_service_1.SessionsService,
        application_state_service_1.ApplicationStateService,
        session_inputs_service_1.SessionInputsService,
        events_gateway_1.EventsGateway,
        chat_service_1.ChatService,
        llm_turn_processor_service_1.LlmTurnProcessorService])
], LlmResponsesService);
//# sourceMappingURL=llm-responses.service.js.map