"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.pulseCronService = void 0;
const client_s3_1 = require("@aws-sdk/client-s3");
const SecretProviderService_1 = require("../../util/secrets/SecretProviderService");
const pulseEvaluationService_1 = require("./pulseEvaluationService");
const pulseService_1 = require("./pulseService");
const pulseCronAWS_1 = require("./pulse/pulseCronAWS");
const lodash_1 = __importDefault(require("lodash"));
const clickhouseService_1 = require("./clickhouseService");
const uuid_1 = require("uuid");
const date_fns_1 = require("date-fns");
const pulseCronAzure_1 = require("./pulse/pulseCronAzure");
const pulseCronCommon_1 = require("./pulse/pulseCronCommon");
const identity_1 = require("@azure/identity");
const cardChat_1 = require("../../providers/outputTransform/bfl/cardChat");
const path_1 = __importDefault(require("path"));
const pulseSessionService_1 = require("./pulseSessionService");
const combinedAudio_1 = require("../../assertions/audio/combinedAudio");
const callControlPlaneApi_1 = require("../../util/callContolPlane/callControlPlaneApi");
const logger_1 = __importDefault(require("../../logger"));
const observeDashboard_1 = require("./observe/observeDashboard");
class PulseCronService {
    /**
     * Evaluate SDK traces for a given application
     * @param startTime - The start time of the evaluation
     * @param endTime - The end time of the evaluation
     * @param applicationId - The ID of the application
     * @param sampleByCount - Whether to sample by count
     * @param sampleByPercentage - Whether to sample by percentage
     * @param samplingRate - The sampling rate
     * @param monitoringConfig - The monitoring configuration for the application
     */
    async getEvaluateSDKTraces({ startTime, endTime, applicationId, sampleByCount, sampleByPercentage, samplingRate, monitoringConfig, application, correlationId, skipMap, orgId, orgRestrictions, renewalNotificationMap, usageNotificationMap, exhaustedNotificationMap, }) {
        const reportsLimit = 100;
        let reportsPage = 1;
        const seed = Math.floor(Math.random() * 1000000);
        if (skipMap?.has(orgId)) {
            return;
        }
        console.log(`Getting evaluate SDK traces with correlation ID: ${JSON.stringify({
            correlationId,
            startTime,
            endTime,
            applicationId,
            sampleByCount,
            sampleByPercentage,
        })}`);
        let reports = await pulseService_1.pulseService.getReportsForCronJob({
            startTime,
            endTime,
            applicationId,
            sampleByCount,
            sampleByPercentage,
            samplingRate,
            limit: reportsLimit,
            page: reportsPage,
            seed,
        });
        while (reports?.length > 0) {
            for (const report of reports) {
                await pulseEvaluationService_1.pulseEvaluationService.runEvaluation({
                    applicationId,
                    traceId: report.TraceId,
                    spans: report.Spans,
                    monitoringConfig,
                    workspaceId: orgId ?? application?.workspaceId,
                    skipMap,
                    orgRestrictions,
                    renewalNotificationMap,
                    usageNotificationMap,
                    exhaustedNotificationMap,
                });
            }
            reportsPage = reportsPage + 1;
            reports = await pulseService_1.pulseService.getReportsForCronJob({
                startTime,
                endTime,
                applicationId,
                sampleByCount,
                sampleByPercentage,
                samplingRate,
                limit: reportsLimit,
                page: reportsPage,
                seed,
            });
        }
    }
    /**
     * Evaluate SDK sessions for a given application
     * @param startTime - The start time of the evaluation
     * @param endTime - The end time of the evaluation
     * @param applicationId - The ID of the application
     * @param sampleByCount - Whether to sample by count
     * @param sampleByPercentage - Whether to sample by percentage
     * @param samplingRate - The sampling rate
     * @param monitoringConfig - The monitoring configuration for the application
     */
    async getEvaluateSDKSessions({ startTime, endTime, applicationId, sampleByCount, sampleByPercentage, samplingRate, monitoringConfig, application, correlationId, skipMap, orgRestrictions, orgId, renewalNotificationMap, usageNotificationMap, exhaustedNotificationMap, }) {
        const pulseSessionService = new pulseSessionService_1.PulseSessionService();
        const reportsLimit = 100;
        let reportsPage = 1;
        const seed = Math.floor(Math.random() * 1000000);
        let sessions = await pulseService_1.pulseService.getSessionsForCronJob({
            startTime,
            endTime,
            applicationId,
            sampleByCount,
            sampleByPercentage,
            samplingRate,
            limit: reportsLimit,
            page: reportsPage,
            seed,
        });
        while (sessions?.length > 0) {
            console.log(`Getting evaluate sessions cron job with correlation ID: ${JSON.stringify({
                correlationId,
                startTime,
                endTime,
                applicationId,
                sampleByCount,
                sampleByPercentage,
                reportsPage,
                seed,
                sessions,
            })}`);
            for (const session of sessions) {
                const spans = await pulseSessionService.getSessionSpans(session.sessionId);
                await pulseEvaluationService_1.pulseEvaluationService.runEvaluation({
                    applicationId,
                    sessionId: session.sessionId,
                    spans: spans,
                    monitoringConfig,
                    workspaceId: orgId ?? application?.workspaceId,
                    skipMap,
                    orgRestrictions,
                    renewalNotificationMap,
                    usageNotificationMap,
                    exhaustedNotificationMap,
                });
            }
            reportsPage = reportsPage + 1;
            sessions = await pulseService_1.pulseService.getSessionsForCronJob({
                startTime,
                endTime,
                applicationId,
                sampleByCount,
                sampleByPercentage,
                samplingRate,
                limit: reportsLimit,
                page: reportsPage,
                seed,
            });
        }
    }
    async evaluateChatLogs({ logContent, applicationId, monitoringConfig, application, service, orgId, skipMap, orgRestrictions, renewalNotificationMap, usageNotificationMap, exhaustedNotificationMap, }) {
        const { key, } = logContent;
        let prompt = [];
        let response = null;
        let provider = null;
        let contentJson = null;
        const file = await service.getFileContent({
            fileName: key,
        });
        let { content, } = file;
        try {
            contentJson = JSON.parse(content);
        }
        catch (error) {
            console.error(error);
        }
        if (application?.provider_type === 'output:transform:bfl:cardChat') {
            provider = new cardChat_1.BflCardChatProvider();
            contentJson = await provider.callApi(content);
        }
        try {
            if (lodash_1.default.isEmpty(contentJson)) {
                throw new Error('Content is empty');
            }
            if (Array.isArray(contentJson)
                && lodash_1.default.isEmpty(contentJson?.[0]?.messages) === false) {
                contentJson = contentJson?.[0]?.messages;
            }
            else if (lodash_1.default.isEmpty(contentJson?.messages) === false
                && Array.isArray(contentJson?.messages)) {
                contentJson = contentJson?.messages;
            }
            else if (contentJson?.output) {
                contentJson = contentJson?.output;
            }
            // Find index of the last 'assistant'
            let lastAssistantIdx = -1;
            for (let i = contentJson.length - 1; i >= 0; i--) {
                if (contentJson[i].role === "assistant") {
                    lastAssistantIdx = i;
                    break;
                }
            }
            if (lastAssistantIdx === -1) {
                response = undefined;
                prompt = contentJson || [];
            }
            else {
                const responseObj = contentJson?.[lastAssistantIdx];
                const promptArr = contentJson?.slice(0, lastAssistantIdx).concat(contentJson?.slice(lastAssistantIdx + 1));
                response = responseObj;
                prompt = promptArr;
            }
            const trace = await this.createTrace({
                logContent,
                applicationId,
                monitoringConfig,
                content: contentJson,
            });
            await pulseEvaluationService_1.pulseEvaluationService.runEvaluation({
                traceId: trace?.TraceId,
                applicationId,
                prompt: [
                    {
                        label: JSON.stringify(prompt),
                        raw: JSON.stringify(prompt),
                    },
                ],
                response: {
                    output: response,
                },
                monitoringConfig,
                application,
                workspaceId: orgId ?? application?.workspaceId,
                skipMap,
                orgRestrictions,
                renewalNotificationMap,
                usageNotificationMap,
                exhaustedNotificationMap,
            });
            // Cleanup large variables to free memory
            content = null;
            contentJson = null;
            prompt = null;
            response = null;
        }
        catch (error) {
            console.error(error);
        }
    }
    generateTraceId() {
        return (0, uuid_1.v4)().replace(/-/g, '');
    }
    generateSpanId() {
        return (0, uuid_1.v4)().replace(/-/g, '')?.slice(0, 16);
    }
    async createTrace({ logContent, applicationId, monitoringConfig, content, }) {
        const { fileType, key, size, lastModified, } = logContent;
        const dbResults = [];
        const fileExtension = path_1.default.extname(key);
        const fileName = path_1.default.basename(key, fileExtension);
        dbResults.push({
            Timestamp: (0, date_fns_1.format)(new Date(lastModified), 'yyyy-MM-dd HH:mm:ss.SSSSSSSSS'),
            TraceId: this.generateTraceId(),
            SpanId: this.generateSpanId(),
            SpanName: `chat-${fileName}`,
            SpanKind: 'SPAN_KIND_CUSTOM',
            ServiceName: applicationId,
            ResourceAttributes: {
                'service.name': applicationId,
                'deployment.environment': 'default',
            },
            ScopeName: 'folder',
            SpanAttributes: {
                'telemetry.sdk.name': 'folder',
                'gen_ai.output.type': fileType,
                'service.name': applicationId,
                'gen_ai.completion': fileType === 'chat' ? JSON.stringify(content) : '',
                'gen_ai.prompt': '',
                'gen_ai.operation.name': 'chat',
                'file.name': path_1.default.basename(key),
                'file.path': key,
                'file.lastModified': lastModified,
                'file.size': size,
            },
            StatusCode: 'STATUS_CODE_UNSET',
            'Events.Timestamp': fileType === 'chat' ? [
                `${(0, date_fns_1.format)(new Date(lastModified), 'yyyy-MM-dd HH:mm:ss.SSSSSSSSS')}`
            ] : [],
            'Events.Name': fileType === 'chat' ? [
                'gen_ai.completion',
            ] : [],
            'Events.Attributes': fileType === 'chat' ? [
                {
                    'gen_ai.completion': JSON.stringify(content),
                },
            ] : [],
            Duration: 0,
        });
        // Insert entries in ClickHouse
        await clickhouseService_1.clickHouseService.insert('otel_traces', dbResults);
        return dbResults?.[0];
    }
    ;
    async evaluateAudioLogs({ logContent, applicationId, monitoringConfig, service, orgId, skipMap, orgRestrictions, renewalNotificationMap, usageNotificationMap, exhaustedNotificationMap, }) {
        const { key, } = logContent;
        try {
            // fetch from s3
            const file = await service.getFileContent({
                fileName: key,
            });
            let { content: content_, transcript: transcript_, } = file;
            const { fileExtension } = file;
            let response = Buffer.from(content_).toString('base64');
            let transcript = transcript_;
            const transcriptDeepgram = await (0, combinedAudio_1.getAudioTranscript)({
                data: response,
                format: fileExtension,
            }, '', orgId);
            await pulseEvaluationService_1.pulseEvaluationService.runEvaluation({
                applicationId,
                prompt: [
                    {
                        label: JSON.stringify(transcript),
                        raw: JSON.stringify(transcript),
                    },
                ],
                response: {
                    audio: {
                        id: logContent.key,
                        data: response,
                        format: fileExtension,
                        transcript,
                    },
                    output: transcriptDeepgram.transcript,
                },
                monitoringConfig,
                workspaceId: orgId,
                skipMap,
                orgRestrictions,
                renewalNotificationMap,
                usageNotificationMap,
                exhaustedNotificationMap,
                logContent,
                createTrace: true,
            });
            // Cleanup large variables to free memory
            content_ = null;
            transcript_ = null;
            transcript = null;
            response = null;
        }
        catch (error) {
            console.error(error);
        }
    }
    /**
     * Upload file through controlplane
     * @param fileName - The name of the file
     * @returns Promise<Record<string, any>> - The response from the controlplane
     */
    async uploadThroughControlplane({ fileName, fileType, serviceProvider, secretName, fullPath, locationUrl, applicationId, }) {
        try {
            const response = await (0, callControlPlaneApi_1.callControlPlane)('/upload/copy?trusysApiKey=mocked', {
                method: 'POST',
                params: {
                    fileName,
                    fileType,
                    serviceProvider,
                    secretName,
                    fullPath,
                    applicationId,
                    locationUrl,
                },
            }, '');
            if (response?.status === 1) {
                return {
                    success: true,
                    response: response?.response?.copy,
                };
            }
            return {
                success: false,
                error: response?.error ?? response?.message,
            };
        }
        catch (error) {
            console.error('Error uploading file through controlplane:', error);
        }
        return {
            success: false,
            error: 'Error uploading file through controlplane',
        };
    }
    async evaluateVideoLogs({ logContent, applicationId, monitoringConfig, service, orgId, skipMap, orgRestrictions, renewalNotificationMap, usageNotificationMap, exhaustedNotificationMap, }) {
        try {
            const { key, fileType, fullPath, } = logContent;
            if (fileType !== 'video') {
                return;
            }
            const file = await this.uploadThroughControlplane({
                fileName: key,
                fileType,
                serviceProvider: monitoringConfig?.serviceProvider,
                secretName: monitoringConfig?.secretName,
                fullPath,
                locationUrl: monitoringConfig?.locationUrl,
                applicationId,
            });
            const { response, success, } = file;
            if (!success) {
                return;
            }
            const { url, } = response;
            await pulseEvaluationService_1.pulseEvaluationService.runEvaluation({
                applicationId,
                prompt: [],
                response: {
                    output: {
                        trusys: {
                            output: [
                                {
                                    type: 'video_url',
                                    video_url: { url },
                                },
                            ],
                        },
                    },
                },
                monitoringConfig,
                workspaceId: orgId,
                skipMap,
                orgRestrictions,
                renewalNotificationMap,
                usageNotificationMap,
                exhaustedNotificationMap,
                logContent,
                createTrace: true,
            });
        }
        catch (error) {
            console.error('Error evaluating video logs:', error);
        }
    }
    async evaluateImageLogs({ logContent, applicationId, monitoringConfig, service, orgId, skipMap, orgRestrictions, renewalNotificationMap, usageNotificationMap, exhaustedNotificationMap, }) {
        try {
            const { key, fileType, fullPath, } = logContent;
            if (fileType !== 'image') {
                return;
            }
            const file = await this.uploadThroughControlplane({
                fileName: key,
                fileType,
                serviceProvider: monitoringConfig?.serviceProvider,
                secretName: monitoringConfig?.secretName,
                fullPath,
                locationUrl: monitoringConfig?.locationUrl,
                applicationId,
            });
            const { response, success, } = file;
            if (!success) {
                return;
            }
            const { url, } = response;
            await pulseEvaluationService_1.pulseEvaluationService.runEvaluation({
                applicationId,
                prompt: [],
                response: {
                    output: {
                        trusys: {
                            output: [
                                {
                                    type: 'image_url',
                                    image_url: { url },
                                },
                            ],
                        },
                    },
                },
                monitoringConfig,
                workspaceId: orgId,
                skipMap,
                orgRestrictions,
                renewalNotificationMap,
                usageNotificationMap,
                exhaustedNotificationMap,
                logContent,
                createTrace: true,
            });
        }
        catch (error) {
            console.error('Error evaluating image logs:', error);
        }
    }
    /**
     * Evaluate AWS Log Streams for a given application
     * @param startTime - The start time of the evaluation
     * @param endTime - The end time of the evaluation
     * @param applicationId - The ID of the application
     * @param monitoringConfig - The monitoring configuration for the application
     * @param secretName - The name of the secret
     * @param secrets - The secrets for the application
     */
    async getEvaluateAWSLogStreams({ startTime, endTime, applicationId, monitoringConfig, secretName, secrets, application, correlationId, orgRestrictions, renewalNotificationMap, usageNotificationMap, exhaustedNotificationMap, skipMap, orgId, }) {
        const { logLocation, serviceProvider, locationUrl, samplingFrequency, samplingCount, samplingPercentage, } = monitoringConfig;
        if (logLocation !== 'folder-path' || serviceProvider !== 'aws') {
            throw new Error('Invalid monitoring configuration');
        }
        const { AWS_ACCESS_KEY_ID: accessKey, AWS_SECRET_ACCESS_KEY: secretKey, AWS_REGION: awsRegion, } = secrets;
        const { bucketName, prefix } = (0, pulseCronCommon_1.parseAwsFolderLocationUrl)(locationUrl);
        const s3 = new client_s3_1.S3({
            region: awsRegion,
            credentials: {
                accessKeyId: accessKey,
                secretAccessKey: secretKey,
            },
        });
        const pulseCronAWS = new pulseCronAWS_1.PulseCronAWS({
            bucketName,
            client: s3,
            prefix,
            maxConcurrentDownloads: 10,
            maxKeys: 100,
            startTime: new Date(startTime),
            endTime: new Date(endTime),
            earlyTermination: false,
            region: awsRegion,
            samplingByCount: samplingFrequency === 'count',
            samplingByPercentage: samplingFrequency === 'percentage',
            samplingCount,
            samplingPercentage,
            applicationId: application?.id,
        });
        const logs = await pulseCronAWS.retrieveLogs();
        const { logContents } = logs;
        let duplicateCount = 0;
        const seenKeys = new Set();
        console.log(`Getting evaluate AWS log streams with correlation ID: ${JSON.stringify({
            correlationId,
            startTime,
            endTime,
            applicationId,
            monitoringConfig,
            duplicateCount,
            seenKeysSize: seenKeys.size,
            seenKeys: seenKeys.values(),
        })}`);
        for (const logContent of logContents) {
            const key = logContent.key;
            if (seenKeys.has(key)) {
                duplicateCount++;
                continue;
            }
            seenKeys.add(key);
        }
        for (const logContent of logContents) {
            if (logContent.fileType === 'audio') {
                await this.evaluateAudioLogs({
                    logContent: logContent,
                    applicationId,
                    monitoringConfig,
                    service: pulseCronAWS,
                    orgId,
                    skipMap,
                    orgRestrictions,
                    renewalNotificationMap,
                    usageNotificationMap,
                    exhaustedNotificationMap,
                });
            }
            if (logContent.fileType === 'chat') {
                await this.evaluateChatLogs({
                    logContent: logContent,
                    applicationId,
                    monitoringConfig,
                    application,
                    service: pulseCronAWS,
                    orgId,
                    skipMap,
                    orgRestrictions,
                    renewalNotificationMap,
                    usageNotificationMap,
                    exhaustedNotificationMap,
                });
            }
            if (logContent.fileType === 'video') {
                await this.evaluateVideoLogs({
                    logContent: logContent,
                    applicationId,
                    monitoringConfig,
                    service: pulseCronAWS,
                    orgId,
                    skipMap,
                    orgRestrictions,
                    renewalNotificationMap,
                    usageNotificationMap,
                    exhaustedNotificationMap,
                });
            }
            if (logContent.fileType === 'image') {
                await this.evaluateImageLogs({
                    logContent: logContent,
                    applicationId,
                    monitoringConfig,
                    service: pulseCronAWS,
                    orgId,
                    skipMap,
                    orgRestrictions,
                    renewalNotificationMap,
                    usageNotificationMap,
                    exhaustedNotificationMap,
                });
            }
        }
    }
    /**
     * Evaluate Azure Log Streams for a given application
     * @param startTime - The start time of the evaluation
     * @param endTime - The end time of the evaluation
     * @param applicationId - The ID of the application
     * @param monitoringConfig - The monitoring configuration for the application
     * @param secretName - The name of the secret
     * @param secrets - The secrets for the application
     */
    async getEvaluateAzureLogStreams({ startTime, endTime, applicationId, monitoringConfig, secretName, secrets, application, correlationId, orgRestrictions, renewalNotificationMap, usageNotificationMap, exhaustedNotificationMap, skipMap, orgId, }) {
        const { logLocation, serviceProvider, locationUrl, samplingFrequency, samplingCount, samplingPercentage, } = monitoringConfig;
        if (logLocation !== 'folder-path' || serviceProvider !== 'azure') {
            throw new Error('Invalid monitoring configuration');
        }
        // Extract Azure Blob Storage information from the URL
        // Parse the URL to extract account name, container name, and prefix
        const urlParts = locationUrl.split('/');
        const hostParts = urlParts[2].split('.');
        const accountName = hostParts[0];
        const containerName = urlParts[3];
        // Handle multilevel folders or empty prefix
        // If there are more parts after container name, join them as prefix
        // If no additional parts, prefix is empty string
        const prefix = urlParts.length > 4 ? urlParts.slice(4).join('/') : '';
        // Get Azure credentials from secrets
        const { AZURE_CLIENT_ID: clientId, AZURE_CLIENT_SECRET: clientSecret, AZURE_TENANT_ID: tenantId, } = secrets;
        const credential = new identity_1.ClientSecretCredential(tenantId, clientId, clientSecret);
        const pulseCronAzure = new pulseCronAzure_1.PulseCronAzure({
            accountName,
            containerName,
            credential,
            prefix, // prefix can be empty string for root container or multilevel path
            maxConcurrentDownloads: 10,
            maxKeys: 100,
            startTime: new Date(startTime),
            endTime: new Date(endTime),
            earlyTermination: false,
            samplingByCount: samplingFrequency === 'count',
            samplingByPercentage: samplingFrequency === 'percentage',
            samplingCount,
            samplingPercentage,
            applicationId: application?.id,
        });
        const logs = await pulseCronAzure.retrieveLogs();
        const { logContents } = logs;
        let duplicateCount = 0;
        const seenKeys = new Set();
        for (const logContent of logContents) {
            const key = logContent.key;
            if (seenKeys.has(key)) {
                duplicateCount++;
                continue;
            }
            seenKeys.add(key);
        }
        console.log(`Getting evaluate Azure log streams with correlation ID: ${JSON.stringify({
            correlationId,
            startTime,
            endTime,
            applicationId,
            monitoringConfig,
            duplicateCount,
            seenKeysSize: seenKeys.size,
            seenKeys: seenKeys.values(),
        })}`);
        for (const logContent of logContents) {
            if (logContent.fileType === 'audio') {
                await this.evaluateAudioLogs({
                    logContent: logContent,
                    applicationId,
                    monitoringConfig,
                    service: pulseCronAzure,
                    orgId,
                    skipMap,
                    orgRestrictions,
                    renewalNotificationMap,
                    usageNotificationMap,
                    exhaustedNotificationMap,
                });
            }
            if (logContent.fileType === 'chat') {
                await this.evaluateChatLogs({
                    logContent: logContent,
                    applicationId,
                    monitoringConfig,
                    application,
                    service: pulseCronAzure,
                    orgId,
                    skipMap,
                    orgRestrictions,
                    renewalNotificationMap,
                    usageNotificationMap,
                    exhaustedNotificationMap,
                });
            }
            if (logContent.fileType === 'video') {
                await this.evaluateVideoLogs({
                    logContent: logContent,
                    applicationId,
                    monitoringConfig,
                    service: pulseCronAzure,
                    orgId,
                    skipMap,
                    orgRestrictions,
                    renewalNotificationMap,
                    usageNotificationMap,
                    exhaustedNotificationMap,
                });
            }
            if (logContent.fileType === 'image') {
                await this.evaluateImageLogs({
                    logContent: logContent,
                    applicationId,
                    monitoringConfig,
                    service: pulseCronAzure,
                    orgId,
                    skipMap,
                    orgRestrictions,
                    renewalNotificationMap,
                    usageNotificationMap,
                    exhaustedNotificationMap,
                });
            }
        }
    }
    /**
     * Evaluate traces for a given application
     * @param startTime - The start time of the evaluation
     * @param endTime - The end time of the evaluation
     * @param applicationId - The ID of the application
     * @param monitoringConfig - The monitoring configuration for the application
     */
    async evaluateApplicationTraces({ startTime, endTime, applicationId, monitoringConfig, application, correlationId, skipMap, orgId, orgRestrictions, renewalNotificationMap, usageNotificationMap, exhaustedNotificationMap, }) {
        const sampleByCount = monitoringConfig?.samplingFrequency === 'count';
        const sampleByPercentage = monitoringConfig?.samplingFrequency === 'percentage';
        const samplingRate = monitoringConfig?.samplingFrequency === 'count' ? monitoringConfig?.samplingCount : monitoringConfig?.samplingPercentage;
        if (skipMap.has(orgId)) {
            logger_1.default.info(`Skipping evaluation for application ${applicationId} because it has exceeded the spans usage limit`);
            return;
        }
        // Check if we need to evaluate SDK traces
        if (monitoringConfig?.logLocation === 'sdk') {
            await this.getEvaluateSDKTraces({
                startTime,
                endTime,
                applicationId,
                sampleByCount,
                sampleByPercentage,
                samplingRate,
                monitoringConfig,
                application,
                correlationId,
                orgRestrictions,
                renewalNotificationMap,
                usageNotificationMap,
                exhaustedNotificationMap,
                skipMap,
                orgId,
            });
        }
        else if (monitoringConfig?.logLocation === 'folder-path'
            && monitoringConfig?.serviceProvider === 'aws') {
            const secretName = monitoringConfig?.secretName;
            const secretProvider = new SecretProviderService_1.SecretProviderService({
                cloudProvider: process.env.CLOUD_PROVIDER || 'azure',
                vault: process.env.DEFAULT_AZURE_VAULT || 'sccentralindiadev',
                region: process.env.DEFAULT_AZURE_REGION || 'ap-south-1',
            });
            const secrets = await secretProvider.getAll(secretName);
            if (!secrets) {
                throw new Error('Secret not found');
            }
            await this.getEvaluateAWSLogStreams({
                startTime,
                endTime,
                applicationId,
                monitoringConfig,
                secretName,
                secrets,
                application,
                correlationId,
                orgRestrictions,
                renewalNotificationMap,
                usageNotificationMap,
                exhaustedNotificationMap,
                skipMap,
                orgId,
            });
        }
        else if (monitoringConfig?.logLocation === 'folder-path'
            && monitoringConfig?.serviceProvider === 'azure') {
            const secretName = monitoringConfig?.secretName;
            const secretProvider = new SecretProviderService_1.SecretProviderService({
                cloudProvider: process.env.CLOUD_PROVIDER || 'azure',
                vault: process.env.DEFAULT_AZURE_VAULT || 'sccentralindiadev',
                region: process.env.DEFAULT_AZURE_REGION || 'ap-south-1',
            });
            const secrets = await secretProvider.getAll(secretName);
            if (!secrets) {
                throw new Error('Secret not found');
            }
            await this.getEvaluateAzureLogStreams({
                startTime,
                endTime,
                applicationId,
                monitoringConfig,
                secretName,
                secrets,
                application,
                correlationId,
                orgRestrictions,
                renewalNotificationMap,
                usageNotificationMap,
                exhaustedNotificationMap,
                skipMap,
                orgId,
            });
        }
        else {
            // TODO: Throw error
        }
    }
    /**
     * Evaluate traces for a given application
     * @param startTime - The start time of the evaluation
     * @param endTime - The end time of the evaluation
     * @param applicationId - The ID of the application
     * @param monitoringConfig - The monitoring configuration for the application
     */
    async evaluateApplicationSessions({ startTime, endTime, applicationId, monitoringConfig, application, correlationId, skipMap, orgRestrictions, orgId, renewalNotificationMap, usageNotificationMap, exhaustedNotificationMap, }) {
        const sampleByCount = monitoringConfig?.samplingFrequency === 'count';
        const sampleByPercentage = monitoringConfig?.samplingFrequency === 'percentage';
        const samplingRate = monitoringConfig?.samplingFrequency === 'count' ? monitoringConfig?.samplingCount : monitoringConfig?.samplingPercentage;
        if (skipMap.has(orgId)) {
            logger_1.default.info(`Skipping evaluation for application ${applicationId} because it has exceeded the spans usage limit`);
            return;
        }
        // Check if we need to evaluate SDK traces
        if (monitoringConfig?.logLocation === 'sdk') {
            await this.getEvaluateSDKSessions({
                startTime,
                endTime,
                applicationId,
                sampleByCount,
                sampleByPercentage,
                samplingRate,
                monitoringConfig,
                application,
                correlationId,
                renewalNotificationMap,
                usageNotificationMap,
                exhaustedNotificationMap,
                skipMap,
                orgRestrictions,
                orgId,
            });
        }
        // else if (
        //   monitoringConfig?.logLocation === 'folder-path'
        //   && monitoringConfig?.serviceProvider === 'aws'
        // ) {
        //   const secretName = monitoringConfig?.secretName;
        //   const secretProvider = new SecretProviderService({
        //     cloudProvider: process.env.CLOUD_PROVIDER || 'azure',
        //     vault: process.env.DEFAULT_AZURE_VAULT || 'sccentralindiadev',
        //     region: process.env.DEFAULT_AZURE_REGION || 'ap-south-1',
        //   });
        //   const secrets = await secretProvider.getAll(secretName);
        //   if (!secrets) {
        //     throw new Error('Secret not found');
        //   }
        //   await this.getEvaluateAWSLogStreams({
        //     startTime,
        //     endTime,
        //     applicationId,
        //     monitoringConfig,
        //     secretName,
        //     secrets,
        //     application,
        //   });
        // } else if (
        //   monitoringConfig?.logLocation === 'folder-path'
        //   && monitoringConfig?.serviceProvider === 'azure'
        // ) {
        //   const secretName = monitoringConfig?.secretName;
        //   const secretProvider = new SecretProviderService({
        //     cloudProvider: process.env.CLOUD_PROVIDER || 'azure',
        //     vault: process.env.DEFAULT_AZURE_VAULT || 'sccentralindiadev',
        //     region: process.env.DEFAULT_AZURE_REGION || 'ap-south-1',
        //   });
        //   const secrets = await secretProvider.getAll(secretName);
        //   if (!secrets) {
        //     throw new Error('Secret not found');
        //   }
        //   await this.getEvaluateAzureLogStreams({
        //     startTime,
        //     endTime,
        //     applicationId,
        //     monitoringConfig,
        //     secretName,
        //     secrets,
        //     application,
        //   });
        // } else {
        //   // TODO: Throw error
        // }
    }
    async observationDashboardPopulate({ startTime, endTime, applicationId, monitoringConfig, application, correlationId, traceIds, }) {
        // If not SDK traces, don't proceed
        if (monitoringConfig?.logLocation !== 'sdk') {
            return;
        }
        const reportsLimit = 100;
        let reportsPage = 1;
        const seed = Math.floor(Math.random() * 1000000);
        let reports = await pulseService_1.pulseService.getObservationReportsForCronJob({
            traceIds,
            startTime,
            endTime,
            applicationId,
            limit: reportsLimit,
            page: reportsPage,
            seed,
        });
        while (reports?.length > 0) {
            for (const report of reports) {
                await observeDashboard_1.observeDashboardService.populateObservationDashboardData({
                    applicationId,
                    traceId: report.TraceId,
                    spans: report.Spans,
                    monitoringConfig,
                    workspaceId: application?.workspaceId,
                    application,
                });
            }
            reportsPage = reportsPage + 1;
            reports = await pulseService_1.pulseService.getObservationReportsForCronJob({
                traceIds,
                startTime,
                endTime,
                applicationId,
                limit: reportsLimit,
                page: reportsPage,
                seed,
            });
        }
    }
}
exports.pulseCronService = new PulseCronService();
//# sourceMappingURL=pulseCronService.js.map