"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getTestRunMetricAnalysisFail = exports.getTestRunMetricAnalysisPass = exports.getTestRunMetricAnalysisTotal = void 0;
const drizzle_orm_1 = require("drizzle-orm");
const database_1 = require("../../../database");
const tables_1 = require("../../../database/tables");
const logger_1 = require("../../../logger");
const getTestRunMetricAnalysisTotal = async (req, res) => {
    try {
        logger_1.logger.info('Get Test Run Metric Analysis Total endpoint called');
        const { testRunId } = req.params;
        const { page = '1', limit = '10', metricName, metricValue } = req.query;
        const parsedLimit = Number(limit);
        const parsedPage = Number(page);
        const offset = (parsedPage - 1) * parsedLimit;
        if (!testRunId) {
            res.status(400).json({
                success: false,
                message: 'testRunId is required',
            });
            return;
        }
        const db = await (0, database_1.getDb)();
        // Verify test run exists
        const testRun = await db
            .select({ id: tables_1.testRunsTable.id })
            .from(tables_1.testRunsTable)
            .where((0, drizzle_orm_1.eq)(tables_1.testRunsTable.id, testRunId))
            .limit(1);
        if (!testRun.length) {
            res.status(404).json({
                success: false,
                message: 'Test run not found',
            });
            return;
        }
        // First get the evalIds for this test run
        const testRunToEvals = await db
            .select({ evalId: tables_1.testRunsToEvalsTable.evalId })
            .from(tables_1.testRunsToEvalsTable)
            .where((0, drizzle_orm_1.eq)(tables_1.testRunsToEvalsTable.testRunId, testRunId));
        const evalIds = testRunToEvals.map((row) => row.evalId);
        if (evalIds.length === 0) {
            res.status(200).json({
                success: true,
                data: {
                    results: [],
                    count: 0,
                },
            });
            return;
        }
        // Build where conditions for eval results
        const whereConditions = [(0, drizzle_orm_1.inArray)(tables_1.evalResultsTable.evalId, evalIds)];
        // Add metric name filter if provided
        if (metricName && !metricValue) {
            whereConditions.push((0, drizzle_orm_1.sql) `EXISTS (
          SELECT 1 
          FROM jsonb_array_elements(${tables_1.evalResultsTable.gradingResult}->'componentResults') AS component
          WHERE (
            component->'assertion'->>'displayLabel' = ${metricName}
            OR component->'assertion'->>'type' = ${metricName}
          )
        )`);
        }
        if (metricValue && metricName) {
            whereConditions.push((0, drizzle_orm_1.sql) `EXISTS (
          SELECT 1 
          FROM jsonb_array_elements(${tables_1.evalResultsTable.gradingResult}->'componentResults') AS component
          WHERE (
            component->'assertion'->>'displayLabel' = ${metricName}
            OR component->'assertion'->>'type' = ${metricName}
          ) AND component->'assertion'->>'output' = ${metricValue}
        )`);
        }
        // Get all eval results for this test run
        const evalResults = await db
            .select({
            id: tables_1.evalResultsTable.id,
            evalId: tables_1.evalResultsTable.evalId,
            prompt: tables_1.evalResultsTable.prompt,
            response: tables_1.evalResultsTable.response,
            gradingResult: tables_1.evalResultsTable.gradingResult,
            success: tables_1.evalResultsTable.success,
            score: tables_1.evalResultsTable.score,
            createdAt: tables_1.evalResultsTable.createdAt,
            metadata: tables_1.evalResultsTable.metadata,
            provider: tables_1.evalResultsTable.provider,
            testCase: tables_1.evalResultsTable.testCase,
        })
            .from(tables_1.evalResultsTable)
            .where((0, drizzle_orm_1.and)(...whereConditions))
            .limit(parsedLimit)
            .offset(offset);
        // Get total count
        const totalCountResult = await db
            .select({ count: (0, drizzle_orm_1.sql) `count(*)` })
            .from(tables_1.evalResultsTable)
            .where((0, drizzle_orm_1.and)(...whereConditions));
        const totalCount = totalCountResult[0]?.count || 0;
        // Transform results to match expected format
        const results = evalResults.map((result) => ({
            id: result.id,
            evalId: result.evalId,
            prompt: result?.provider?.id === 'phone' ? { raw: 'Phone call' } : result.prompt,
            response: result.response,
            gradingResult: result.gradingResult,
            success: result.success,
            score: result.score,
            createdAt: result.createdAt,
            metadata: result.metadata,
            provider: result.provider,
            testCase: result.testCase,
        }));
        res.json({
            success: true,
            data: {
                results,
                count: totalCount,
                page: parsedPage,
                limit: parsedLimit,
            },
        });
    }
    catch (error) {
        logger_1.logger.error(`Error in get test run metric analysis total controller: ${error}`);
        res.status(500).json({
            success: false,
            message: 'Internal server error',
        });
    }
};
exports.getTestRunMetricAnalysisTotal = getTestRunMetricAnalysisTotal;
const getTestRunMetricAnalysisPass = async (req, res) => {
    try {
        logger_1.logger.info('Get Test Run Metric Analysis Pass endpoint called');
        const { testRunId } = req.params;
        const { page = '1', limit = '10', metricName } = req.query;
        const parsedLimit = Number(limit);
        const parsedPage = Number(page);
        const offset = (parsedPage - 1) * parsedLimit;
        if (!testRunId) {
            res.status(400).json({
                success: false,
                message: 'testRunId is required',
            });
            return;
        }
        const db = await (0, database_1.getDb)();
        // Verify test run exists
        const testRun = await db
            .select({ id: tables_1.testRunsTable.id })
            .from(tables_1.testRunsTable)
            .where((0, drizzle_orm_1.eq)(tables_1.testRunsTable.id, testRunId))
            .limit(1);
        if (!testRun.length) {
            res.status(404).json({
                success: false,
                message: 'Test run not found',
            });
            return;
        }
        // First get the evalIds for this test run
        const testRunToEvals = await db
            .select({ evalId: tables_1.testRunsToEvalsTable.evalId })
            .from(tables_1.testRunsToEvalsTable)
            .where((0, drizzle_orm_1.eq)(tables_1.testRunsToEvalsTable.testRunId, testRunId));
        const evalIds = testRunToEvals.map((row) => row.evalId);
        if (evalIds.length === 0) {
            res.status(200).json({
                success: true,
                data: {
                    results: [],
                    count: 0,
                },
            });
            return;
        }
        // Build where conditions for eval results
        const whereConditions = [(0, drizzle_orm_1.inArray)(tables_1.evalResultsTable.evalId, evalIds)];
        // Add metric name filter if provided
        if (metricName) {
            whereConditions.push((0, drizzle_orm_1.sql) `EXISTS (
          SELECT 1 
          FROM jsonb_array_elements(${tables_1.evalResultsTable.gradingResult}->'componentResults') AS component
          WHERE (
            (component->'assertion'->>'displayLabel' = ${metricName}
              OR component->'assertion'->>'type' = ${metricName})
            AND component->>'pass' = 'true'
          )
        )`);
        }
        // Get passed eval results for this test run
        const evalResults = await db
            .select({
            id: tables_1.evalResultsTable.id,
            evalId: tables_1.evalResultsTable.evalId,
            prompt: tables_1.evalResultsTable.prompt,
            response: tables_1.evalResultsTable.response,
            gradingResult: tables_1.evalResultsTable.gradingResult,
            success: tables_1.evalResultsTable.success,
            score: tables_1.evalResultsTable.score,
            createdAt: tables_1.evalResultsTable.createdAt,
            metadata: tables_1.evalResultsTable.metadata,
            provider: tables_1.evalResultsTable.provider,
            testCase: tables_1.evalResultsTable.testCase,
        })
            .from(tables_1.evalResultsTable)
            .where((0, drizzle_orm_1.and)(...whereConditions))
            .limit(parsedLimit)
            .offset(offset);
        // Get total count for passed results
        const totalCountResult = await db
            .select({ count: (0, drizzle_orm_1.sql) `count(*)` })
            .from(tables_1.evalResultsTable)
            .where((0, drizzle_orm_1.and)(...whereConditions));
        const totalCount = totalCountResult[0]?.count || 0;
        // Transform results to match expected format
        const results = evalResults.map((result) => ({
            id: result.id,
            evalId: result.evalId,
            prompt: result?.provider?.id === 'phone' ? { raw: 'Phone call' } : result.prompt,
            response: result.response,
            gradingResult: result.gradingResult,
            success: result.success,
            score: result.score,
            createdAt: result.createdAt,
            metadata: result.metadata,
            provider: result.provider,
            testCase: result.testCase,
        }));
        res.json({
            success: true,
            data: {
                results,
                count: totalCount,
                page: parsedPage,
                limit: parsedLimit,
            },
        });
    }
    catch (error) {
        logger_1.logger.error(`Error in get test run metric analysis pass controller: ${error}`);
        res.status(500).json({
            success: false,
            message: 'Internal server error',
        });
    }
};
exports.getTestRunMetricAnalysisPass = getTestRunMetricAnalysisPass;
const getTestRunMetricAnalysisFail = async (req, res) => {
    try {
        logger_1.logger.info('Get Test Run Metric Analysis Fail endpoint called');
        const { testRunId } = req.params;
        const { page = '1', limit = '10', metricName } = req.query;
        const parsedLimit = Number(limit);
        const parsedPage = Number(page);
        const offset = (parsedPage - 1) * parsedLimit;
        if (!testRunId) {
            res.status(400).json({
                success: false,
                message: 'testRunId is required',
            });
            return;
        }
        const db = await (0, database_1.getDb)();
        // Verify test run exists
        const testRun = await db
            .select({ id: tables_1.testRunsTable.id })
            .from(tables_1.testRunsTable)
            .where((0, drizzle_orm_1.eq)(tables_1.testRunsTable.id, testRunId))
            .limit(1);
        if (!testRun.length) {
            res.status(404).json({
                success: false,
                message: 'Test run not found',
            });
            return;
        }
        // First get the evalIds for this test run
        const testRunToEvals = await db
            .select({ evalId: tables_1.testRunsToEvalsTable.evalId })
            .from(tables_1.testRunsToEvalsTable)
            .where((0, drizzle_orm_1.eq)(tables_1.testRunsToEvalsTable.testRunId, testRunId));
        const evalIds = testRunToEvals.map((row) => row.evalId);
        if (evalIds.length === 0) {
            res.status(200).json({
                success: true,
                data: {
                    results: [],
                    count: 0,
                },
            });
            return;
        }
        // Build where conditions for eval results
        const whereConditions = [(0, drizzle_orm_1.inArray)(tables_1.evalResultsTable.evalId, evalIds)];
        // Add metric name filter if provided
        if (metricName) {
            whereConditions.push((0, drizzle_orm_1.sql) `EXISTS (
          SELECT 1 
          FROM jsonb_array_elements(${tables_1.evalResultsTable.gradingResult}->'componentResults') AS component
          WHERE (
            (component->'assertion'->>'displayLabel' = ${metricName}
              OR component->'assertion'->>'type' = ${metricName})
            AND component->>'pass' = 'false'
          )
        )`);
        }
        // Get failed eval results for this test run
        const evalResults = await db
            .select({
            id: tables_1.evalResultsTable.id,
            evalId: tables_1.evalResultsTable.evalId,
            prompt: tables_1.evalResultsTable.prompt,
            response: tables_1.evalResultsTable.response,
            gradingResult: tables_1.evalResultsTable.gradingResult,
            success: tables_1.evalResultsTable.success,
            score: tables_1.evalResultsTable.score,
            createdAt: tables_1.evalResultsTable.createdAt,
            metadata: tables_1.evalResultsTable.metadata,
            provider: tables_1.evalResultsTable.provider,
            testCase: tables_1.evalResultsTable.testCase,
        })
            .from(tables_1.evalResultsTable)
            .where((0, drizzle_orm_1.and)(...whereConditions))
            .limit(parsedLimit)
            .offset(offset);
        // Get total count for failed results
        const totalCountResult = await db
            .select({ count: (0, drizzle_orm_1.sql) `count(*)` })
            .from(tables_1.evalResultsTable)
            .where((0, drizzle_orm_1.and)(...whereConditions));
        const totalCount = totalCountResult[0]?.count || 0;
        // Transform results to match expected format
        const results = evalResults.map((result) => ({
            id: result.id,
            evalId: result.evalId,
            prompt: result?.provider?.id === 'phone' ? { raw: 'Phone call' } : result.prompt,
            response: result.response,
            gradingResult: result.gradingResult,
            success: result.success,
            score: result.score,
            createdAt: result.createdAt,
            metadata: result.metadata,
            provider: result.provider,
            testCase: result.testCase,
        }));
        res.json({
            success: true,
            data: {
                results,
                count: totalCount,
                page: parsedPage,
                limit: parsedLimit,
            },
        });
    }
    catch (error) {
        logger_1.logger.error(`Error in get test run metric analysis fail controller: ${error}`);
        res.status(500).json({
            success: false,
            message: 'Internal server error',
        });
    }
};
exports.getTestRunMetricAnalysisFail = getTestRunMetricAnalysisFail;
//# sourceMappingURL=get-test-run-metric-analysis.js.map