"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getUserInput = exports.getScenario = exports.getUserProfile = void 0;
const conversationSimulator_1 = require("../../../conversationSimulator/conversationSimulator");
const defaults_1 = require("../../../providers/defaults");
const logger_1 = __importDefault(require("../../../logger"));
/**
 * Repair malformed JSON by closing unterminated strings and objects
 */
function repairJsonString(jsonString) {
    let repaired = jsonString.trim();
    // Track if we're inside a string
    let inString = false;
    let escapeNext = false;
    let braceDepth = 0;
    let bracketDepth = 0;
    for (let i = 0; i < repaired.length; i++) {
        const char = repaired[i];
        if (escapeNext) {
            escapeNext = false;
            continue;
        }
        if (char === '\\') {
            escapeNext = true;
            continue;
        }
        if (char === '"' && !escapeNext) {
            inString = !inString;
        }
        else if (!inString) {
            if (char === '{') {
                braceDepth++;
            }
            if (char === '}') {
                braceDepth--;
            }
            if (char === '[') {
                bracketDepth++;
            }
            if (char === ']') {
                bracketDepth--;
            }
        }
    }
    // If we're still in a string at the end, close it
    if (inString) {
        repaired += '"';
    }
    // Close any unclosed braces/brackets
    while (braceDepth > 0) {
        repaired += '}';
        braceDepth--;
    }
    while (bracketDepth > 0) {
        repaired += ']';
        bracketDepth--;
    }
    return repaired;
}
async function parseJsonResponse(content) {
    // Check if the response is wrapped in markdown code blocks
    const markdownJsonMatch = content.match(/```(?:json)?\s*(\{[\s\S]*?\})\s*```/);
    let jsonString = content;
    if (markdownJsonMatch) {
        jsonString = markdownJsonMatch[1];
    }
    // Convert Python-style booleans to JavaScript booleans
    jsonString = jsonString.replace(/\bFalse\b/g, 'false').replace(/\bTrue\b/g, 'true');
    try {
        return JSON.parse(jsonString);
    }
    catch (err) {
        // Attempt to repair malformed JSON
        try {
            const repairedJson = repairJsonString(jsonString);
            return JSON.parse(repairedJson);
        }
        catch (repairErr) {
            /* logger.error(
              `Failed to parse JSON response (original and repaired): ${JSON.stringify({
                original: jsonString.substring(0, 500),
                error: err instanceof Error ? err.message : String(err),
                repairError: repairErr instanceof Error ? repairErr.message : String(repairErr),
              })}`, */
            /* ); */
            logger_1.default.error('');
            throw new Error(`Failed to parse JSON: ${err instanceof Error ? err.message : String(err)}`);
        }
    }
}
const getUserProfile = async (req, res) => {
    try {
        const { userProfileItems, language = 'English', orgId } = req.body;
        if (!userProfileItems || !Array.isArray(userProfileItems)) {
            res.status(400).json({
                error: 'userProfileItems is required and must be an array',
            });
            return;
        }
        const prompt = conversationSimulator_1.ConversationSimulatorTemplate.generateUserProfile(userProfileItems, language);
        const azureProvider = (await (0, defaults_1.getDefaultProviders)(undefined, orgId)).synthesizeProvider;
        const response = await azureProvider.callApi(prompt);
        if (response.error) {
            res.status(500).json({
                error: `Azure API error: ${response.error}`,
            });
            return;
        }
        const content = response.output;
        if (typeof content !== 'string') {
            res.status(500).json({
                error: 'Unexpected response format from Azure provider',
            });
            return;
        }
        const json = await parseJsonResponse(content);
        const userProfile = json.user_profile;
        if (!userProfile || typeof userProfile !== 'string') {
            res.status(500).json({
                error: 'Invalid response format: missing user_profile',
            });
            return;
        }
        res.json({
            userProfile,
            cost: response.cost ?? 0,
            tokenUsage: response.tokenUsage ?? {
                prompt: 0,
                completion: 0,
                total: 0,
                cached: 0,
            },
        });
    }
    catch (error) {
        logger_1.default.error(`Error in getUserProfile: ${error}`);
        res.status(500).json({
            error: error instanceof Error ? error.message : 'Internal server error',
        });
    }
};
exports.getUserProfile = getUserProfile;
const getScenario = async (req, res) => {
    try {
        const { userProfile, intent, language = 'English', orgId } = req.body;
        if (!userProfile || typeof userProfile !== 'string') {
            res.status(400).json({
                error: 'userProfile is required and must be a string',
            });
            return;
        }
        if (!intent || typeof intent !== 'string') {
            res.status(400).json({
                error: 'intent is required and must be a string',
            });
            return;
        }
        const prompt = conversationSimulator_1.ConversationSimulatorTemplate.generateScenario(userProfile, intent, language);
        const defaultProviders = await (0, defaults_1.getDefaultProviders)(undefined, orgId);
        const azureProvider = defaultProviders.synthesizeProvider;
        const response = await azureProvider.callApi(prompt);
        if (response.error) {
            res.status(500).json({
                error: `Azure API error: ${response.error}`,
            });
            return;
        }
        const content = response.output;
        if (typeof content !== 'string') {
            res.status(500).json({
                error: 'Unexpected response format from Azure provider',
            });
            return;
        }
        const json = await parseJsonResponse(content);
        const scenario = json.scenario;
        if (!scenario || typeof scenario !== 'string') {
            res.status(500).json({
                error: 'Invalid response format: missing scenario',
            });
            return;
        }
        res.json({
            scenario,
            cost: response.cost ?? 0,
            tokenUsage: response.tokenUsage ?? {
                prompt: 0,
                completion: 0,
                total: 0,
                cached: 0,
            },
        });
    }
    catch (error) {
        logger_1.default.error(`Error in getScenario: ${error}`);
        res.status(500).json({
            error: error instanceof Error ? error.message : 'Internal server error',
        });
    }
};
exports.getScenario = getScenario;
const getUserInput = async (req, res) => {
    try {
        const { scenario, userProfile, conversationHistory, language = 'English', orgId } = req.body;
        if (!scenario || typeof scenario !== 'string') {
            res.status(400).json({
                error: 'scenario is required and must be a string',
            });
            return;
        }
        if (!userProfile || typeof userProfile !== 'string') {
            res.status(400).json({
                error: 'userProfile is required and must be a string',
            });
            return;
        }
        const defaultProviders = await (0, defaults_1.getDefaultProviders)(undefined, orgId);
        const azureProvider = defaultProviders.synthesizeProvider;
        let prompt;
        //let json: any;
        if (conversationHistory && Array.isArray(conversationHistory) && conversationHistory.length > 0) {
            // Generate next user input
            const historyJson = JSON.stringify(conversationHistory, null, 2);
            prompt = conversationSimulator_1.ConversationSimulatorTemplate.generateNextUserInput(scenario, userProfile, historyJson, language);
        }
        else {
            // Generate first user input
            prompt = conversationSimulator_1.ConversationSimulatorTemplate.generateFirstInput(scenario, userProfile, language);
        }
        const response = await azureProvider.callApi(prompt);
        if (response.error) {
            res.status(500).json({
                error: `Azure API error: ${response.error}`,
            });
            return;
        }
        const content = response.output;
        if (typeof content !== 'string') {
            res.status(500).json({
                error: 'Unexpected response format from Azure provider',
            });
            return;
        }
        const json = await parseJsonResponse(content);
        const simulatedInput = json.simulated_input;
        if (!simulatedInput || typeof simulatedInput !== 'string') {
            res.status(500).json({
                error: 'Invalid response format: missing simulated_input',
            });
            return;
        }
        res.json({
            userInput: simulatedInput,
            cost: response.cost ?? 0,
            tokenUsage: response.tokenUsage ?? {
                prompt: 0,
                completion: 0,
                total: 0,
                cached: 0,
            },
        });
    }
    catch (error) {
        logger_1.default.error(`Error in getUserInput: ${error}`);
        res.status(500).json({
            error: error instanceof Error ? error.message : 'Internal server error',
        });
    }
};
exports.getUserInput = getUserInput;
//# sourceMappingURL=conversationSimulator.js.map