"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getTestRunAudioMetricAnalysis = void 0;
const drizzle_orm_1 = require("drizzle-orm");
const database_1 = require("../../../database");
const tables_1 = require("../../../database/tables");
const lodash_1 = __importDefault(require("lodash"));
const getTestRunAudioMetricAnalysis = 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: [],
            });
            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,
                        expected: component?.assertion?.expected || '',
                        actual: component?.assertion?.actual || '',
                        pass: component?.pass || false,
                        score: component?.score || 0,
                        reason: component?.reason || '',
                    });
                }
            });
        });
        const totalRecords = result.length;
        let passedRecords = 0;
        let failedRecords = 0;
        if (result.length > 0) {
            result.forEach((item) => {
                if (item.pass) {
                    passedRecords++;
                }
                else {
                    failedRecords++;
                }
            });
        }
        else {
            res.json({
                success: true,
                data: [],
            });
            return;
        }
        // Handle different metrics based on metricName
        let processedData = [];
        if (metricName === 'audio-sentiment') {
            const outcomes = {};
            result.forEach((item) => {
                const sentiment = item.reason?.toLowerCase() || '';
                if (!outcomes[sentiment]) {
                    outcomes[sentiment] = 0;
                }
                if (lodash_1.default.isEmpty(sentiment)) {
                    const output = item?.output?.toLowerCase() || '';
                    if (!outcomes[output]) {
                        outcomes[output] = 0;
                    }
                    outcomes[output]++;
                }
                else {
                    outcomes[sentiment]++;
                }
            });
            processedData = Object.entries(outcomes).map(([outcome, count]) => ({
                outcome,
                count,
                total: totalRecords,
                passed: passedRecords,
                failed: failedRecords,
            }));
        }
        else if (metricName === 'audio-background-noise') {
            const outcomes = {
                low: 0,
                medium: 0,
                high: 0,
            };
            result.forEach((item) => {
                const noiseLevel = item.reason?.toLowerCase() || '';
                if (noiseLevel.includes('low')) {
                    outcomes.low++;
                }
                else if (noiseLevel.includes('medium')) {
                    outcomes.medium++;
                }
                else if (noiseLevel.includes('high')) {
                    outcomes.high++;
                }
                else {
                    outcomes.medium++;
                }
            });
            processedData = [
                {
                    outcome: 'Low',
                    count: outcomes.low,
                    total: totalRecords,
                    passed: passedRecords,
                    failed: failedRecords,
                },
                {
                    outcome: 'Medium',
                    count: outcomes.medium,
                    total: totalRecords,
                    passed: passedRecords,
                    failed: failedRecords,
                },
                {
                    outcome: 'High',
                    count: outcomes.high,
                    total: totalRecords,
                    passed: passedRecords,
                    failed: failedRecords,
                },
            ];
        }
        else {
            // For other metrics, extract unique values from reason field
            const outcomeCounts = {};
            result.forEach((item) => {
                const outcome = item.reason || 'Unknown';
                outcomeCounts[outcome] = (outcomeCounts[outcome] || 0) + 1;
            });
            processedData = Object.entries(outcomeCounts).map(([outcome, count]) => ({
                outcome,
                count,
                total: totalRecords,
                passed: passedRecords,
                failed: failedRecords,
            }));
        }
        res.json({
            success: true,
            data: processedData,
        });
    }
    catch (error) {
        console.error('Error in getTestRunAudioMetricAnalysis:', error);
        res.status(500).json({
            success: false,
            message: 'Error fetching audio metric analysis',
            error,
        });
    }
};
exports.getTestRunAudioMetricAnalysis = getTestRunAudioMetricAnalysis;
//# sourceMappingURL=get-test-run-audio-metric-analysis.js.map