"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.codeExecutionAssertion = codeExecutionAssertion;
const buffer_1 = require("buffer");
const judge0_1 = require("../util/judge0");
// Map all supported languages to their Judge0 IDs
const languageMap = {
    python: 71,
    c: 50,
    'c++': 54,
    cpp: 54,
    go: 60,
    java: 62,
    javascript: 63,
    js: 63,
};
async function codeExecutionAssertion(params) {
    const { output, context, assertion } = params;
    const vars = context.vars || {};
    // Force language to string and lowercase
    const langRaw = vars.language;
    const langKey = typeof langRaw === 'string' ? langRaw.toLowerCase() : undefined;
    if (!langKey || !languageMap[langKey]) {
        return {
            pass: false,
            score: 0,
            reason: `❌ Unsupported language: ${String(vars.language)}`,
            assertion,
        };
    }
    const languageId = languageMap[langKey];
    console.log('🔢 languageId =', languageId);
    // Ensure output is string before regex match
    let code = typeof output === 'string' ? output : JSON.stringify(output);
    const match = code.match(/```(?:\w+)?\s*([\s\S]*?)```/m);
    if (match) {
        code = match[1].trim();
    }
    console.log('🔍 Final code to execute:\n', code);
    const encodedCode = buffer_1.Buffer.from(String(code), 'utf-8').toString('base64');
    const encodedStdin = buffer_1.Buffer.from(String(vars.test_input ?? ''), 'utf-8').toString('base64');
    const expectedOutput = String(vars.expected_output ?? '').trim();
    const result = await (0, judge0_1.createSubmission)({
        languageId,
        sourceCodeBase64: encodedCode,
        stdinBase64: encodedStdin,
        wait: true,
    });
    console.log('📦 Result from RapidAPI:', result);
    const status = result?.status?.id;
    if (status !== 3) {
        const errorMsg = buffer_1.Buffer.from(result?.compile_output || result?.stderr || '', 'base64').toString();
        return {
            pass: false,
            score: 0,
            reason: `❌ Failed [${result?.status?.description}]: ${errorMsg}`,
            assertion,
        };
    }
    const actualOutput = buffer_1.Buffer.from(result.stdout || '', 'base64')
        .toString()
        .trim();
    const pass = actualOutput === expectedOutput;
    const score = pass ? 1 : 0;
    const reason = pass
        ? `Output matched with expected result "${actualOutput}"`
        : `Expected "${expectedOutput}", but got "${actualOutput}"`;
    console.log('acutual output: ', actualOutput);
    console.log('Assertion: ', assertion);
    return { assertion, pass, score, reason };
}
//# sourceMappingURL=codeExecuation.js.map