"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.GuardrailsController = void 0;
const logger_1 = require("../../logger");
const index_1 = require("../../guardrails/index");
const gaurdRailsService_1 = require("../services/gaurdRailsService");
class GuardrailsController {
    static async batch(req, res) {
        try {
            const body = req.body;
            // Validate request body
            if (!body.scanners || !Array.isArray(body.scanners) || body.scanners.length === 0) {
                res.status(400).json({
                    success: false,
                    error: 'scanners array is required and must not be empty',
                });
                return;
            }
            if (!body.content) {
                res.status(400).json({
                    success: false,
                    error: 'content is required',
                });
                return;
            }
            const outputString = body.content.response || '';
            // Process each scanner
            const results = await Promise.all(body.scanners.map(async (scanner) => {
                const guardrailType = scanner.scanner_type;
                // Create a minimal assertion object
                const assertion = {
                    type: guardrailType, // Using guardrails as a placeholder type
                    config: scanner.config || {},
                };
                try {
                    const result = await (0, index_1.runGuardrails)({
                        guardrailTypes: [guardrailType],
                        assertion,
                        outputString,
                        prompt: body.content.prompt,
                        config: scanner.config,
                        context: body.scan_context,
                    });
                    return result[0] || {
                        pass: false,
                        score: 0,
                        reason: 'Guardrail check failed',
                        assertion,
                    };
                }
                catch (error) {
                    logger_1.logger.error(`Error processing scanner ${scanner.scanner_type}: ${error}`);
                    return {
                        pass: false,
                        score: 0,
                        reason: `Error: ${String(error)}`,
                        assertion,
                    };
                }
            }));
            res.json({
                success: true,
                data: {
                    application_id: body.application_id,
                    results,
                },
            });
        }
        catch (error) {
            logger_1.logger.error(`Error in guardrails batch: ${error}`);
            res.status(500).json({
                success: false,
                error: 'Failed to process guardrails batch request',
            });
        }
    }
    static async getApplicationGaurdRailConfig(req, res) {
        try {
            const applicationId = req.query.applicationId;
            const projectId = req.query.projectId;
            const name = req.query.name;
            const guardrailsConfig = await gaurdRailsService_1.GuardRailsService.getApplicationGaurdRailConfig(applicationId, projectId, name);
            res.json(guardrailsConfig);
        }
        catch (error) {
            logger_1.logger.error(`Error fetching application gaurdrails config: ${error}`);
            res.status(500).json({
                success: false,
                message: `Failed to fetch  application gaurdrails config: ${error}`,
            });
        }
    }
    static async saveResults(req, res) {
        try {
            const body = req.body;
            const projectId = body?.projectId ?? req.query.projectId;
            const orgId = body?.orgId ?? req.query.orgId;
            const results = Array.isArray(body) ? body : body?.results;
            if (!Array.isArray(results) || results.length === 0) {
                res.status(400).json({
                    success: false,
                    message: 'results array is required',
                });
                return;
            }
            await gaurdRailsService_1.GuardRailsService.saveGuardrailResults(results, projectId, orgId);
            res.json({
                success: true,
                message: 'Guardrail results saved successfully',
            });
        }
        catch (error) {
            logger_1.logger.error(`Error saving guardrail results: ${error}`);
            res.status(500).json({
                success: false,
                message: `Failed to save guardrail results: ${error}`,
            });
        }
    }
    static async fetchResults(req, res) {
        try {
            const applicationId = req.query.applicationId;
            const projectId = req.query.projectId;
            const start = req.query.start || '';
            const end = req.query.end || '';
            if (!applicationId || !projectId || !start || !end) {
                res.status(400).json({
                    success: false,
                    message: 'applicationId, projectId, start and end query params are required',
                });
                return;
            }
            const data = await gaurdRailsService_1.GuardRailsService.fetchGuardrailResults({
                applicationId,
                projectId,
                start,
                end,
            });
            res.json({
                success: true,
                data,
            });
        }
        catch (error) {
            logger_1.logger.error(`Error fetching guardrail results: ${error}`);
            res.status(500).json({
                success: false,
                message: 'Failed to fetch guardrail results',
            });
        }
    }
    // Dashboard metrics for Guardrails dashboard widgets - Total Requests
    static async getTotalRequestsMetrics(req, res) {
        try {
            const applicationId = req.query.applicationId;
            const projectId = req.query.projectId;
            const start = req.query.start || '';
            const end = req.query.end || '';
            const guardrailType = req.query.guardrailType || 'all';
            const version = req.query.version || '';
            const environment = req.query.environment || '';
            if (!applicationId || !projectId || !start || !end) {
                res.status(400).json({
                    success: false,
                    message: 'applicationId, projectId, start and end query params are required',
                });
                return;
            }
            const data = await gaurdRailsService_1.GuardRailsService.getTotalRequestsMetrics({
                applicationId,
                projectId,
                start,
                end,
                guardrailType,
                version,
                environment,
            });
            res.json({
                success: true,
                data,
            });
        }
        catch (error) {
            logger_1.logger.error(`Error fetching guardrail total-requests metrics: ${error}`);
            res.status(500).json({
                success: false,
                message: 'Failed to fetch guardrail total-requests metrics',
            });
        }
    }
    // Guardrail latency (time-series, with percentiles)
    static async getLatencyMetrics(req, res) {
        try {
            const applicationId = req.query.applicationId;
            const projectId = req.query.projectId;
            const start = req.query.start || '';
            const end = req.query.end || '';
            const guardrailType = req.query.guardrailType || 'all';
            const version = req.query.version || '';
            const environment = req.query.environment || '';
            if (!applicationId || !projectId || !start || !end) {
                res.status(400).json({
                    success: false,
                    message: 'applicationId, projectId, start and end query params are required',
                });
                return;
            }
            const data = await gaurdRailsService_1.GuardRailsService.getLatencyMetrics({
                applicationId,
                projectId,
                start,
                end,
                guardrailType,
                version,
                environment,
            });
            res.json({
                success: true,
                data,
            });
        }
        catch (error) {
            logger_1.logger.error(`Error fetching guardrail latency metrics: ${error}`);
            res.status(500).json({
                success: false,
                message: 'Failed to fetch guardrail latency metrics',
            });
        }
    }
    // Latency histogram for input / output rails
    static async getLatencyHistogramMetrics(req, res) {
        try {
            const applicationId = req.query.applicationId;
            const projectId = req.query.projectId;
            const start = req.query.start || '';
            const end = req.query.end || '';
            const guardrailType = req.query.guardrailType || 'all';
            const version = req.query.version || '';
            const environment = req.query.environment || '';
            if (!applicationId || !projectId || !start || !end) {
                res.status(400).json({
                    success: false,
                    message: 'applicationId, projectId, start and end query params are required',
                });
                return;
            }
            const data = await gaurdRailsService_1.GuardRailsService.getLatencyHistogramMetrics({
                applicationId,
                projectId,
                start,
                end,
                guardrailType,
                version,
                environment,
            });
            res.json({
                success: true,
                data,
            });
        }
        catch (error) {
            logger_1.logger.error(`Error fetching guardrail latency-histogram metrics: ${error}`);
            res.status(500).json({
                success: false,
                message: 'Failed to fetch guardrail latency-histogram metrics',
            });
        }
    }
    // Guardrail analysis widget (summary + exceptions + category failures)
    static async getAnalysisMetrics(req, res) {
        try {
            const applicationId = req.query.applicationId;
            const projectId = req.query.projectId;
            const start = req.query.start || '';
            const end = req.query.end || '';
            const guardrailType = req.query.guardrailType || 'all';
            const version = req.query.version || '';
            const environment = req.query.environment || '';
            if (!applicationId || !projectId || !start || !end) {
                res.status(400).json({
                    success: false,
                    message: 'applicationId, projectId, start and end query params are required',
                });
                return;
            }
            const data = await gaurdRailsService_1.GuardRailsService.getAnalysisMetrics({
                applicationId,
                projectId,
                start,
                end,
                guardrailType,
                version,
                environment,
            });
            res.json({
                success: true,
                data,
            });
        }
        catch (error) {
            logger_1.logger.error(`Error fetching guardrail analysis metrics: ${error}`);
            res.status(500).json({
                success: false,
                message: 'Failed to fetch guardrail analysis metrics',
            });
        }
    }
    // Request summary for donut chart (total requests and total errors)
    static async getRequestSummaryMetrics(req, res) {
        try {
            const applicationId = req.query.applicationId;
            const projectId = req.query.projectId;
            const start = req.query.start || '';
            const end = req.query.end || '';
            const guardrailType = req.query.guardrailType || 'all';
            const version = req.query.version || '';
            const environment = req.query.environment || '';
            if (!applicationId || !projectId || !start || !end) {
                res.status(400).json({
                    success: false,
                    message: 'applicationId, projectId, start and end query params are required',
                });
                return;
            }
            const data = await gaurdRailsService_1.GuardRailsService.getRequestSummaryMetrics({
                applicationId,
                projectId,
                start,
                end,
                guardrailType,
                version,
                environment,
            });
            res.json({
                success: true,
                data,
            });
        }
        catch (error) {
            logger_1.logger.error(`Error fetching guardrail request summary metrics: ${error}`);
            res.status(500).json({
                success: false,
                message: 'Failed to fetch guardrail request summary metrics',
            });
        }
    }
    /**
     * Dashboard metrics by requested slice. Query param `metrics` = comma-separated
     * list of: summary | exceptionsOverTime | categoryFailures.
     * Returns only the requested parts to avoid redundant data.
     */
    static async getDashboardMetrics(req, res) {
        try {
            const applicationId = req.query.applicationId;
            const projectId = req.query.projectId;
            const start = req.query.start || '';
            const end = req.query.end || '';
            const guardrailType = req.query.guardrailType || 'all';
            const version = req.query.version || '';
            const environment = req.query.environment || '';
            const metricsParam = req.query.metrics || '';
            if (!applicationId || !projectId || !start || !end) {
                res.status(400).json({
                    success: false,
                    message: 'applicationId, projectId, start and end query params are required',
                });
                return;
            }
            const requested = new Set(metricsParam.split(',').map((m) => m.trim().toLowerCase()).filter(Boolean));
            const params = {
                applicationId,
                projectId,
                start,
                end,
                guardrailType,
                version,
                environment,
            };
            const data = {};
            if (requested.has('summary')) {
                const result = await gaurdRailsService_1.GuardRailsService.getSummaryMetricsOnly(params);
                Object.assign(data, result);
            }
            if (requested.has('exceptionsovertime')) {
                const result = await gaurdRailsService_1.GuardRailsService.getExceptionsOverTimeOnly(params);
                Object.assign(data, result);
            }
            if (requested.has('categoryfailures')) {
                const result = await gaurdRailsService_1.GuardRailsService.getCategoryFailureMetricsOnly(params);
                Object.assign(data, result);
            }
            res.json({
                success: true,
                data,
            });
        }
        catch (error) {
            logger_1.logger.error(`Error fetching guardrail dashboard metrics: ${error}`);
            res.status(500).json({
                success: false,
                message: 'Failed to fetch guardrail dashboard metrics',
            });
        }
    }
    // Latency by validator metrics
    static async getLatencyByValidatorMetrics(req, res) {
        try {
            const applicationId = req.query.applicationId;
            const projectId = req.query.projectId;
            const start = req.query.start || '';
            const end = req.query.end || '';
            const guardrailType = req.query.guardrailType || 'all';
            const version = req.query.version || '';
            const environment = req.query.environment || '';
            if (!applicationId || !projectId || !start || !end) {
                res.status(400).json({
                    success: false,
                    message: 'applicationId, projectId, start and end query params are required',
                });
                return;
            }
            const data = await gaurdRailsService_1.GuardRailsService.getLatencyByValidatorMetrics({
                applicationId,
                projectId,
                start,
                end,
                guardrailType,
                version,
                environment,
            });
            res.json({
                success: true,
                data,
            });
        }
        catch (error) {
            logger_1.logger.error(`Error fetching guardrail latency by validator metrics: ${error}`);
            res.status(500).json({
                success: false,
                message: 'Failed to fetch guardrail latency by validator metrics',
            });
        }
    }
    // Validation failures list for ValidationFailuresPanel
    static async getValidationFailures(req, res) {
        try {
            const applicationId = req.query.applicationId;
            const projectId = req.query.projectId;
            const start = req.query.start || '';
            const end = req.query.end || '';
            const guardrailType = req.query.guardrailType || 'all';
            const version = req.query.version || '';
            const environment = req.query.environment || '';
            const search = req.query.search || '';
            const page = Number.parseInt(req.query.page || '1', 10);
            const limit = Number.parseInt(req.query.limit || '10', 10);
            const sortBy = req.query.sortBy || 'recent';
            const category = req.query.category || '';
            const stage = req.query.stage || '';
            const passStatus = req.query.passStatus || '';
            if (!applicationId || !projectId || !start || !end) {
                res.status(400).json({
                    success: false,
                    message: 'applicationId, projectId, start and end query params are required',
                });
                return;
            }
            const data = await gaurdRailsService_1.GuardRailsService.getValidationFailures({
                applicationId,
                projectId,
                start,
                end,
                guardrailType,
                version,
                environment,
                search,
                page,
                limit,
                sortBy,
                category,
                stage,
                passStatus,
            });
            res.json({
                success: true,
                data,
            });
        }
        catch (error) {
            logger_1.logger.error(`Error fetching guardrail validation failures: ${error}`);
            res.status(500).json({
                success: false,
                message: 'Failed to fetch guardrail validation failures',
            });
        }
    }
    // Download validation failures as CSV
    static async downloadValidationFailuresCSV(req, res) {
        try {
            const applicationId = req.body.applicationId;
            const projectId = req.body.projectId;
            const start = req.body.start || '';
            const end = req.body.end || '';
            const guardrailType = req.body.guardrailType || 'all';
            const version = req.body.version || '';
            const environment = req.body.environment || '';
            const search = req.body.search || '';
            const sortBy = req.body.sortBy || 'recent';
            const category = req.body.category || '';
            const stage = req.body.stage || '';
            if (!applicationId || !projectId || !start || !end) {
                res.status(400).json({
                    success: false,
                    message: 'applicationId, projectId, start and end are required',
                });
                return;
            }
            const failures = await gaurdRailsService_1.GuardRailsService.getAllValidationFailuresForDownload({
                applicationId,
                projectId,
                start,
                end,
                guardrailType,
                version,
                environment,
                search,
                sortBy,
                category,
                stage,
            });
            // Helper function to escape CSV values
            const escapeCsv = (value) => {
                if (value === null || value === undefined) {
                    return '';
                }
                const str = String(value);
                return `"${str.replace(/"/g, '""').replace(/\n/g, ' ').replace(/\r/g, ' ')}"`;
            };
            // CSV headers
            const headers = [
                'Validator ID',
                'Date',
                'Category',
                'Stage',
                'Prompt',
                'Response',
                'Reason',
                'Latency (ms)',
                'Score',
                'App Version',
                'Environment',
            ];
            // Set headers for CSV download
            res.setHeader('Content-Type', 'text/csv; charset=utf-8');
            res.setHeader('Content-Disposition', `attachment; filename="validation-failures-${Date.now()}.csv"`);
            res.setHeader('Cache-Control', 'no-cache');
            // Write BOM for Excel compatibility
            res.write('\uFEFF');
            res.write(headers.map(h => escapeCsv(h)).join(',') + '\n');
            // Write data rows
            for (const failure of failures) {
                const component = failure.component || {};
                const assertion = component.assertion || {};
                const row = [
                    failure.id || '',
                    failure.created_at ? new Date(failure.created_at).toISOString() : '',
                    assertion.type || '',
                    failure.guardrail_stage || '',
                    failure.prompt || '',
                    failure.response || '',
                    component.reason || '',
                    component.latency || failure.latency || 0,
                    component.score || '',
                    failure.app_version || '',
                    failure.environment || '',
                ];
                res.write(row.map(cell => escapeCsv(cell)).join(',') + '\n');
            }
            res.end();
        }
        catch (error) {
            logger_1.logger.error(`Error downloading guardrail validation failures CSV: ${error}`);
            if (res.headersSent) {
                res.end();
            }
            else {
                res.status(500).json({
                    success: false,
                    message: 'Failed to download validation failures CSV',
                });
            }
        }
    }
    static async getValidationFailureDetails(req, res) {
        try {
            const id = req.query.id;
            const applicationId = req.query.applicationId;
            const projectId = req.query.projectId;
            if (!id || !applicationId || !projectId) {
                res.status(400).json({
                    success: false,
                    message: 'id, applicationId, and projectId query params are required',
                });
                return;
            }
            const data = await gaurdRailsService_1.GuardRailsService.getValidationFailureDetails({
                id,
                applicationId,
                projectId,
            });
            if (!data) {
                res.status(404).json({
                    success: false,
                    message: 'Validation failure not found',
                });
                return;
            }
            res.json({
                success: true,
                data,
            });
        }
        catch (error) {
            logger_1.logger.error(`Error fetching guardrail validation failure details: ${error}`);
            res.status(500).json({
                success: false,
                message: 'Failed to fetch guardrail validation failure details',
            });
        }
    }
}
exports.GuardrailsController = GuardrailsController;
//# sourceMappingURL=guardrails.js.map