"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConversationSimulatorApiClient = exports.getTestRunDetails = exports.securityTestRunHandler = exports.getSecurityConfigDetails = exports.generateRedteamConfigTrusysRemote = exports.runTestSuite = exports.getPrompLibraryDetils = exports.getGeneratedTestSuite = exports.getApplicationDetils = void 0;
const logger_1 = __importDefault(require("../logger"));
const apiCall_1 = require("../util/apiCall");
const DEFAULT_HEADERS = {
    'Content-Type': 'application/json',
    Accept: 'application/json',
    'X-Requested-With': 'XMLHttpRequest',
};
const createTestRun = async (testSuite, apiKey, apiHost, projectId) => {
    try {
        const apiUrl = `${apiHost}/api/test-runs`;
        const result = await (0, apiCall_1.apiCall)({
            method: 'POST',
            params: {
                ...testSuite,
                projectId,
            },
            headers: {
                ...DEFAULT_HEADERS,
                'x-api-key': apiKey,
            },
        }, apiUrl);
        return result;
    }
    catch (error) {
        logger_1.default.error(`❌ Error while test run: ${error}`);
        return null;
    }
};
const postTestEvalWithJobId = async (jobId, apiKey, apiHost, projectId) => {
    try {
        const apiUrl = `${apiHost}/api/eval/job/${jobId}/`;
        const result = await (0, apiCall_1.apiCall)({
            method: 'GET',
            params: {
                jobId,
                projectId,
            },
            headers: {
                ...DEFAULT_HEADERS,
                'x-api-key': apiKey,
            },
        }, apiUrl);
        return result;
    }
    catch (error) {
        logger_1.default.error(`❌ Error while test run: ${error}`);
        return null;
    }
};
//eval calls
const getApplicationDetils = async (appName, apiKey, apiHost, projectId) => {
    try {
        const apiUrl = `${apiHost}/api/applications/details`;
        const result = await (0, apiCall_1.apiCall)({
            method: 'GET',
            params: {
                name: appName,
                projectId,
            },
            headers: {
                ...DEFAULT_HEADERS,
                'x-api-key': apiKey,
            },
        }, apiUrl);
        if (result.error) {
            logger_1.default.error(`❌ Error fetching application details: ${result.error}`);
            return null;
        }
        return result;
    }
    catch (error) {
        logger_1.default.error(`❌ Error fetching application details: ${error}`);
        return null;
    }
};
exports.getApplicationDetils = getApplicationDetils;
const getGeneratedTestSuite = async (testSuite, apiKey, apiHost, projectId, parentPromptId) => {
    try {
        const apiUrl = `${apiHost}/api/test-runs/generateTestSuite`;
        const result = await (0, apiCall_1.apiCall)({
            method: 'POST',
            params: {
                ...testSuite,
                projectId,
                parentPromptId,
            },
            headers: {
                ...DEFAULT_HEADERS,
                'x-api-key': apiKey,
            },
        }, apiUrl);
        if (result.error) {
            logger_1.default.error(`❌ Error generating test suite: ${result.error}`);
            return null;
        }
        return result;
    }
    catch (error) {
        logger_1.default.error(`❌ Error generating test suite: ${error}`);
        return null;
    }
};
exports.getGeneratedTestSuite = getGeneratedTestSuite;
const getPrompLibraryDetils = async (libraryName, apiKey, apiHost, projectId) => {
    try {
        const apiUrl = `${apiHost}/api/prompts-library/details`;
        const result = await (0, apiCall_1.apiCall)({
            method: 'GET',
            params: {
                name: libraryName,
                projectId,
            },
            headers: {
                ...DEFAULT_HEADERS,
                'x-api-key': apiKey,
            },
        }, apiUrl);
        if (result.error) {
            logger_1.default.error(`❌ Error fetching prompt library details: ${result.error}`);
            return null;
        }
        return result;
    }
    catch (error) {
        logger_1.default.error(`❌ Error fetching prompt library details: ${error}`);
        return null;
    }
};
exports.getPrompLibraryDetils = getPrompLibraryDetils;
const runTestSuite = async (testSuite, apiKey, apiHost, projectId) => {
    try {
        const response = await createTestRun(testSuite, apiKey, apiHost, projectId);
        if (!response.id) {
            logger_1.default.error(`❌ Error running test suite - ${response?.error ?? ''}`);
            return { success: false, error: response?.error };
        }
        const job = response;
        return new Promise((resolve) => {
            const intervalId = setInterval(async () => {
                const progressResponse = await postTestEvalWithJobId(job.id, apiKey, apiHost, projectId);
                if (!progressResponse.status) {
                    clearInterval(intervalId);
                    logger_1.default.error(`❌ Error running test suite - ${progressResponse?.error}`);
                    resolve({ success: false, error: progressResponse?.error });
                    return;
                }
                const progressData = progressResponse;
                if (progressData.status === 'complete') {
                    clearInterval(intervalId);
                    resolve({ success: true, testRunId: job.testRunId });
                }
                else if (progressData.status === 'failed') {
                    clearInterval(intervalId);
                    logger_1.default.error(`❌ Job failed`);
                    resolve({ success: false, error: 'Job failed' });
                }
                else {
                    const percent = progressData.total === 0
                        ? 0
                        : Math.round((progressData.progress / progressData.total) * 100);
                    // logger.info(`Status from progressResponse: ${JSON.stringify(progressResponse.status)} `);
                    logger_1.default.info(`Eval Percent: ${percent}%`);
                }
            }, 1000);
        });
    }
    catch (error) {
        logger_1.default.error(`❌ An error occurred: ${error.message}`);
        return { success: false, error: error.message };
    }
};
exports.runTestSuite = runTestSuite;
//security calls
const runSecurityTest = async (reqBody, // You can replace 'any' with a more specific type if available
apiHost, apiKey, projectId) => {
    try {
        const apiUrl = `${apiHost}/api/redteam/run`;
        const result = await (0, apiCall_1.apiCall)({
            method: 'POST',
            params: {
                ...reqBody,
                projectId,
            },
            headers: {
                ...DEFAULT_HEADERS,
                'x-api-key': apiKey,
            },
        }, apiUrl);
        if (result.error) {
            logger_1.default.error(`❌ Error while security run: ${result.error}`);
            return null;
        }
        return result;
    }
    catch (error) {
        logger_1.default.error(`❌ Error while security run: ${error}`);
        return null;
    }
};
const generateRedteamConfigTrusysRemote = async (configYaml, commandLineOptions, apiKey, apiHost, projectId) => {
    try {
        const apiUrl = `${apiHost}/api/redteam/generate-config`;
        const result = await (0, apiCall_1.apiCall)({
            method: 'POST',
            params: {
                configYaml,
                commandLineOptions: commandLineOptions || {},
                projectId,
            },
            headers: {
                ...DEFAULT_HEADERS,
                'x-api-key': apiKey,
            },
        }, apiUrl);
        if (result?.error) {
            logger_1.default.error(`❌ Error generating redteam config: ${result.error}`);
            return null;
        }
        return result;
    }
    catch (error) {
        logger_1.default.error(`❌ Error generating redteam config: ${error}`);
        return null;
    }
};
exports.generateRedteamConfigTrusysRemote = generateRedteamConfigTrusysRemote;
const getSecurityConfigDetails = async (securityConfigName, apiKey, apiHost, projectId) => {
    try {
        const apiUrl = `${apiHost}/api/redteam/config/details`;
        const result = await (0, apiCall_1.apiCall)({
            method: 'GET',
            params: {
                name: securityConfigName,
                projectId,
            },
            headers: {
                ...DEFAULT_HEADERS,
                'x-api-key': apiKey,
            },
        }, apiUrl);
        if (result.error) {
            logger_1.default.error(`❌ Error fetching security config details: ${result.error}`);
            return null;
        }
        return result;
    }
    catch (error) {
        logger_1.default.error(`❌ Error fetching security config details: ${error}`);
        return null;
    }
};
exports.getSecurityConfigDetails = getSecurityConfigDetails;
const securityTestRunHandler = async (testSuite, apiHost, apiKey, projectId) => {
    try {
        const response = await runSecurityTest(testSuite, apiHost, apiKey, projectId);
        if (response?.error || !response?.id) {
            logger_1.default.error(`❌ Error running security test - ${response?.error ?? ''}`);
            return null;
        }
        const job = response;
        return new Promise((resolve) => {
            const intervalId = setInterval(async () => {
                const progressResponse = await postTestEvalWithJobId(job.id, apiKey, apiHost, projectId);
                // logger.info(`Response from progressResponse: ${JSON.stringify(progressResponse)} `);
                if (!progressResponse.status) {
                    clearInterval(intervalId);
                    logger_1.default.error(`❌ Error running test suite - ${progressResponse?.error}`);
                    resolve({ success: false, error: progressResponse?.error });
                    return;
                }
                const progressData = progressResponse;
                if (progressData.status === 'complete') {
                    clearInterval(intervalId);
                    logger_1.default.info(`Security Eval Progress: 100% `);
                    resolve({ success: true, testRunId: job.testRunId });
                }
                else if (progressData.status === 'failed') {
                    clearInterval(intervalId);
                    logger_1.default.error(`❌ Job failed`);
                    resolve({ success: false, error: 'Job failed' });
                }
                else {
                    const percent = progressData.total === 0
                        ? 0
                        : Math.round((progressData.progress / progressData.total) * 100);
                    logger_1.default.info(`Security Eval Progress: ${percent}% `);
                }
            }, 1000);
        });
    }
    catch (error) {
        console.error('❌ Error running security test:', error);
    }
};
exports.securityTestRunHandler = securityTestRunHandler;
const getTestRunDetails = async (testRunId, apiKey, apiHost, projectId) => {
    try {
        const apiUrl = `${apiHost}/api/test-runs/write/${testRunId}`;
        const result = await (0, apiCall_1.apiCall)({
            method: 'GET',
            params: {
                projectId,
            },
            headers: {
                ...DEFAULT_HEADERS,
                'x-api-key': apiKey,
            },
        }, apiUrl);
        if (result.error) {
            logger_1.default.error(`❌ Error fetching test run details: ${result.error}`);
            return null;
        }
        return result;
    }
    catch (error) {
        logger_1.default.error(`❌ Error fetching test run details: ${error}`);
        return null;
    }
};
exports.getTestRunDetails = getTestRunDetails;
/**
 * API client class for conversation simulator endpoints
 */
class ConversationSimulatorApiClient {
    constructor(apiKey, apiHost, projectId) {
        this.apiKey = apiKey;
        this.apiHost = apiHost;
        this.projectId = projectId;
    }
    async getUserProfile(intent, userProfileItems) {
        try {
            const apiUrl = `${this.apiHost}/api/simulate/conversation-simulator/user-profile`;
            const result = await (0, apiCall_1.apiCall)({
                method: 'POST',
                params: {
                    userProfileItems: userProfileItems || [],
                    language: 'English',
                },
                headers: {
                    ...DEFAULT_HEADERS,
                    'x-api-key': this.apiKey,
                },
            }, apiUrl);
            if (result.error) {
                logger_1.default.error(`❌ Error fetching user profile: ${result.error}`);
                throw new Error(`Failed to get user profile: ${result.error}`);
            }
            if (!result.userProfile || typeof result.userProfile !== 'string') {
                throw new Error('Invalid user profile response format');
            }
            return {
                userProfile: result.userProfile,
                cost: result.cost,
                tokenUsage: result.tokenUsage,
            };
        }
        catch (error) {
            logger_1.default.error(`❌ Error fetching user profile: ${error}`);
            throw error;
        }
    }
    async getScenario(userProfile, intent) {
        try {
            const apiUrl = `${this.apiHost}/api/simulate/conversation-simulator/scenario`;
            const result = await (0, apiCall_1.apiCall)({
                method: 'POST',
                params: {
                    userProfile,
                    intent,
                    language: 'English',
                },
                headers: {
                    ...DEFAULT_HEADERS,
                    'x-api-key': this.apiKey,
                },
            }, apiUrl);
            if (result.error) {
                logger_1.default.error(`❌ Error fetching scenario: ${result.error}`);
                throw new Error(`Failed to get scenario: ${result.error}`);
            }
            if (!result.scenario || typeof result.scenario !== 'string') {
                throw new Error('Invalid scenario response format');
            }
            return {
                scenario: result.scenario,
                cost: result.cost,
                tokenUsage: result.tokenUsage,
            };
        }
        catch (error) {
            logger_1.default.error(`❌ Error fetching scenario: ${error}`);
            throw error;
        }
    }
    async getUserInput(scenario, userProfile, conversationHistory) {
        try {
            const apiUrl = `${this.apiHost}/api/simulate/conversation-simulator/user-input`;
            const result = await (0, apiCall_1.apiCall)({
                method: 'POST',
                params: {
                    scenario,
                    userProfile,
                    conversationHistory: conversationHistory || [],
                    language: 'English',
                },
                headers: {
                    ...DEFAULT_HEADERS,
                    'x-api-key': this.apiKey,
                },
            }, apiUrl);
            if (result.error) {
                logger_1.default.error(`❌ Error fetching user input: ${result.error}`);
                throw new Error(`Failed to get user input: ${result.error}`);
            }
            if (!result.userInput || typeof result.userInput !== 'string') {
                throw new Error('Invalid user input response format');
            }
            return {
                userInput: result.userInput,
                cost: result.cost,
                tokenUsage: result.tokenUsage,
            };
        }
        catch (error) {
            logger_1.default.error(`❌ Error fetching user input: ${error}`);
            throw error;
        }
    }
}
exports.ConversationSimulatorApiClient = ConversationSimulatorApiClient;
//# sourceMappingURL=callServer.js.map