"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 LlmCallLogsService_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.LlmCallLogsService = void 0;
const common_1 = require("@nestjs/common");
const typeorm_1 = require("@nestjs/typeorm");
const typeorm_2 = require("typeorm");
const llm_call_log_entity_1 = require("../core-entities/llm-call-log.entity");
const LIST_SELECT_COLUMNS = [
    'llm_call_log.id',
    'llm_call_log.session_input_id',
    'llm_call_log.provider',
    'llm_call_log.model_id',
    'llm_call_log.status_code',
    'llm_call_log.latency_ms',
    'llm_call_log.input_tokens',
    'llm_call_log.output_tokens',
    'llm_call_log.cached_tokens',
    'llm_call_log.created_at',
];
let LlmCallLogsService = LlmCallLogsService_1 = class LlmCallLogsService {
    constructor(llmCallLogsRepository) {
        this.llmCallLogsRepository = llmCallLogsRepository;
        this.logger = new common_1.Logger(LlmCallLogsService_1.name);
    }
    async createLog(createLlmCallLogDto) {
        this.logger.log(`Creating LLM call log for session input ${createLlmCallLogDto.session_input_id}`);
        const newLog = this.llmCallLogsRepository.create(createLlmCallLogDto);
        return this.llmCallLogsRepository.save(newLog);
    }
    async updateLog(id, updates) {
        await this.llmCallLogsRepository.update(id, updates);
        const log = await this.llmCallLogsRepository.findOneBy({ id });
        if (!log) {
            throw new Error(`LlmCallLog with ID "${id}" not found`);
        }
        return log;
    }
    async findAll(params) {
        const queryBuilder = this.llmCallLogsRepository.createQueryBuilder('llm_call_log');
        if (params.sessionId) {
            queryBuilder.innerJoin('llm_call_log.sessionInput', 'session_input', 'session_input.session_id = :sessionId', { sessionId: params.sessionId });
        }
        if (params.sessionInputId) {
            queryBuilder.andWhere('llm_call_log.session_input_id = :sessionInputId', {
                sessionInputId: params.sessionInputId,
            });
        }
        if (params.provider) {
            queryBuilder.andWhere('llm_call_log.provider = :provider', {
                provider: params.provider,
            });
        }
        if (params.status === 'success') {
            queryBuilder.andWhere('llm_call_log.status_code >= :minSuccess AND llm_call_log.status_code < :maxSuccess', {
                minSuccess: 200,
                maxSuccess: 300,
            });
        }
        else if (params.status === 'error') {
            queryBuilder.andWhere('(llm_call_log.status_code < :minSuccess OR llm_call_log.status_code >= :maxSuccess OR llm_call_log.status_code IS NULL)', {
                minSuccess: 200,
                maxSuccess: 300,
            });
        }
        const total = await queryBuilder.getCount();
        if (params.offset) {
            queryBuilder.skip(params.offset);
        }
        if (params.limit) {
            queryBuilder.take(params.limit);
        }
        queryBuilder.orderBy('llm_call_log.created_at', 'DESC');
        queryBuilder.select(LIST_SELECT_COLUMNS);
        const logs = await queryBuilder.getMany();
        return { logs, total };
    }
    async findBySessionInputId(sessionInputId, limit, offset) {
        const queryBuilder = this.llmCallLogsRepository
            .createQueryBuilder('llm_call_log')
            .where('llm_call_log.session_input_id = :sessionInputId', {
            sessionInputId,
        })
            .orderBy('llm_call_log.created_at', 'DESC')
            .select(LIST_SELECT_COLUMNS);
        const total = await queryBuilder.getCount();
        if (offset)
            queryBuilder.skip(offset);
        if (limit)
            queryBuilder.take(limit);
        const logs = await queryBuilder.getMany();
        return { logs, total };
    }
    async findBySessionId(sessionId, limit, offset) {
        const queryBuilder = this.llmCallLogsRepository
            .createQueryBuilder('llm_call_log')
            .innerJoin('llm_call_log.sessionInput', 'session_input', 'session_input.session_id = :sessionId', { sessionId })
            .orderBy('llm_call_log.created_at', 'DESC')
            .select(LIST_SELECT_COLUMNS);
        const total = await queryBuilder.getCount();
        if (offset)
            queryBuilder.skip(offset);
        if (limit)
            queryBuilder.take(limit);
        const logs = await queryBuilder.getMany();
        return { logs, total };
    }
    async findById(id) {
        const log = await this.llmCallLogsRepository.findOneBy({ id });
        if (!log) {
            throw new Error(`LlmCallLog with ID "${id}" not found`);
        }
        return log;
    }
};
exports.LlmCallLogsService = LlmCallLogsService;
exports.LlmCallLogsService = LlmCallLogsService = LlmCallLogsService_1 = __decorate([
    (0, common_1.Injectable)(),
    __param(0, (0, typeorm_1.InjectRepository)(llm_call_log_entity_1.LlmCallLog)),
    __metadata("design:paramtypes", [typeorm_2.Repository])
], LlmCallLogsService);
//# sourceMappingURL=llm-call-logs.service.js.map