"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getTestRunAudioMetricTimeAnalysis = void 0;
const drizzle_orm_1 = require("drizzle-orm");
const database_1 = require("../../../database");
const tables_1 = require("../../../database/tables");
const getTestRunAudioMetricTimeAnalysis = async (req, res) => {
    try {
        const { testRunId, metricName } = req.params;
        const { applicationId } = req.query;
        if (!testRunId || !metricName) {
            res.status(400).json({
                success: false,
                message: 'testRunId and metricName are required',
            });
            return;
        }
        const db = (0, database_1.getDb)();
        // Get eval IDs for this test run
        const testRunEvals = await db
            .select({ evalId: tables_1.testRunsToEvalsTable.evalId })
            .from(tables_1.testRunsToEvalsTable)
            .where((0, drizzle_orm_1.eq)(tables_1.testRunsToEvalsTable.testRunId, testRunId));
        if (testRunEvals.length === 0) {
            res.json({
                success: true,
                data: {
                    lineData: [],
                    donutData: [],
                },
            });
            return;
        }
        const evalIds = testRunEvals.map((rel) => rel.evalId);
        // Build where conditions
        const whereConditions = [
            (0, drizzle_orm_1.inArray)(tables_1.evalResultsTable.evalId, evalIds),
            (0, drizzle_orm_1.eq)(tables_1.evalResultsTable.isRedteam, 0),
        ];
        if (applicationId) {
            whereConditions.push((0, drizzle_orm_1.eq)(tables_1.evalResultsTable.applicationId, applicationId));
        }
        // Get all eval results for this test run
        const evalResults = await db
            .select({
            gradingResult: tables_1.evalResultsTable.gradingResult,
        })
            .from(tables_1.evalResultsTable)
            .where((0, drizzle_orm_1.and)(...whereConditions));
        // Process the results similar to pulseService
        const result = [];
        evalResults.forEach((evalResult) => {
            if (!evalResult.gradingResult?.componentResults) {
                return;
            }
            const componentResults = Array.isArray(evalResult.gradingResult.componentResults)
                ? evalResult.gradingResult.componentResults
                : [];
            componentResults.forEach((component) => {
                const assertionType = component?.assertion?.displayLabel || component?.assertion?.type || '';
                if (assertionType === metricName) {
                    result.push({
                        assertion_type: assertionType,
                        assertion_expected: component?.assertion?.expected || '',
                        assertion_actual: component?.assertion?.actual || '',
                        pass: component?.pass || false,
                        score: component?.score || 0,
                        reason: component?.reason || '',
                    });
                }
            });
        });
        // Process the data to calculate response time distribution and pass/fail rates
        const responseTimeData = [];
        const passFailData = {
            Pass: 0,
            Fail: 0,
        };
        if (result.length > 0) {
            // Calculate pass/fail counts
            result.forEach((item) => {
                if (item.pass) {
                    passFailData.Pass++;
                }
                else {
                    passFailData.Fail++;
                }
            });
            if (metricName === 'audio-talk-to-listen-ratio') {
                // For audio-talk-to-listen-ratio, reason field contains values between 0 and 1
                const ratioBuckets = {};
                result.forEach((item) => {
                    try {
                        if (item.reason) {
                            const ratio = Number.parseFloat(item.reason);
                            if (!Number.isNaN(ratio) && ratio >= 0 && ratio <= 1) {
                                // Round to 2 decimal places for bucketing
                                const bucket = Math.round(ratio * 100) / 100;
                                ratioBuckets[bucket] = (ratioBuckets[bucket] || 0) + 1;
                            }
                        }
                    }
                    catch {
                        // If parsing fails, skip this item
                    }
                });
                // Convert buckets to array format
                Object.keys(ratioBuckets).forEach((bucket) => {
                    const bucketNum = Number.parseFloat(bucket);
                    responseTimeData.push({
                        responseTime: bucketNum,
                        avgCount: ratioBuckets[bucketNum],
                        maxCount: ratioBuckets[bucketNum],
                    });
                });
                // Sort by ratio value
                responseTimeData.sort((a, b) => a.responseTime - b.responseTime);
            }
            else {
                // For audio-agent-response-time, create response time buckets for the line chart
                const timeBuckets = {};
                result.forEach((item) => {
                    // Parse the reason field to get average and max values
                    let average = 0;
                    let max = 0;
                    try {
                        if (item.reason) {
                            const reasonData = typeof item.reason === 'string' ? JSON.parse(item.reason) : item.reason;
                            average = Number.parseInt(reasonData.average) || 0;
                            max = Number.parseInt(reasonData.max) || 0;
                        }
                    }
                    catch {
                        // If parsing fails, fallback to 0
                        average = 0;
                        max = 0;
                    }
                    // Use average for the main response time bucket
                    const avgBucket = average;
                    const maxBucket = max;
                    // Count for average distribution
                    if (!timeBuckets[avgBucket]) {
                        timeBuckets[avgBucket] = { avgCount: 0, maxCount: 0 };
                    }
                    timeBuckets[avgBucket].avgCount++;
                    // Count for max distribution
                    if (!timeBuckets[maxBucket]) {
                        timeBuckets[maxBucket] = { avgCount: 0, maxCount: 0 };
                    }
                    timeBuckets[maxBucket].maxCount++;
                });
                // Convert buckets to array format
                Object.keys(timeBuckets).forEach((bucket) => {
                    const bucketNum = Number.parseInt(bucket);
                    responseTimeData.push({
                        responseTime: bucketNum,
                        avgCount: timeBuckets[bucketNum].avgCount,
                        maxCount: timeBuckets[bucketNum].maxCount,
                    });
                });
                // Sort by response time
                responseTimeData.sort((a, b) => a.responseTime - b.responseTime);
            }
        }
        res.json({
            success: true,
            data: {
                lineData: responseTimeData,
                donutData: [
                    { label: 'Pass', value: passFailData.Pass, color: '#3b82f6' },
                    { label: 'Fail', value: passFailData.Fail, color: '#fbbf24' },
                ],
            },
        });
    }
    catch (error) {
        console.error('Error in getTestRunAudioMetricTimeAnalysis:', error);
        res.status(500).json({
            success: false,
            message: 'Error fetching audio metric time analysis',
            error,
        });
    }
};
exports.getTestRunAudioMetricTimeAnalysis = getTestRunAudioMetricTimeAnalysis;
//# sourceMappingURL=get-test-run-audio-metric-time-analysis.js.map