"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.executeAndGradeCode = executeAndGradeCode;
const child_process_1 = require("child_process");
const path_1 = __importDefault(require("path"));
/**
 * Calls the Python script code_executor.py to execute and grade LLM-generated code.
 *
 * @param llmOutput The raw output from the LLM, expected to contain a code block.
 * @param context The context object containing test variables (language, test_input, expected_output, etc.).
 * @returns A promise that resolves to a GradingResult.
 */
async function executeAndGradeCode(llmOutput, assertion, context) {
    console.log('executeAndGradeCode called.');
    console.log('  LLM Output (first 100 chars):', llmOutput.substring(0, 100) + (llmOutput.length > 100 ? '...' : ''));
    console.log('  Context:', JSON.stringify(context, null, 2));
    const pythonScriptPath = path_1.default.join(__dirname, 'python', 'validate_and_run_code.py');
    console.log('Constructed Python script path:', pythonScriptPath);
    // The LLM output might be a string that contains a code block.
    // The context object contains structured test data.
    const llmOutputJsonString = JSON.stringify(llmOutput);
    const contextJsonString = JSON.stringify(context);
    console.log('JSONified LLM Output (truncated):', llmOutputJsonString.substring(0, 100) + '...');
    console.log('JSONified Context (truncated):', contextJsonString.substring(0, 100) + '...');
    const jsonPromise = new Promise((resolve, reject) => {
        const pythonProcessArguments = [pythonScriptPath, llmOutputJsonString, contextJsonString];
        console.log('Spawning Python process with arguments (first arg truncated):', pythonProcessArguments[0], pythonProcessArguments[1].substring(0, 50) + '...', pythonProcessArguments[2].substring(0, 50) + '...');
        const py = (0, child_process_1.spawn)('python', pythonProcessArguments, {
            env: process.env, // Pass current environment variables to the child process
            stdio: ['pipe', 'pipe', 'pipe'], // Capture stdin, stdout, and stderr
        });
        let stdoutData = '';
        let stderrData = '';
        py.stdout.on('data', (chunk) => {
            const chunkStr = chunk.toString();
            stdoutData += chunkStr;
        });
        py.stderr.on('data', (chunk) => {
            const chunkStr = chunk.toString();
            stderrData += chunkStr;
            console.error('Python stderr chunk:', chunkStr);
        });
        py.on('close', (code) => {
            console.log('Python process closed with code:', code);
            if (code === 0) {
                if (stdoutData.trim()) {
                    // Check if stdout actually contains data
                    console.log('Python script succeeded. Raw stdout:', stdoutData.trim());
                    resolve(stdoutData.trim());
                }
                else {
                    // If Python exits with 0 but no output, it's an unexpected scenario for this setup
                    reject(new Error('Python script succeeded but produced no JSON output on stdout.'));
                }
            }
            else {
                const errorMessage = `code_executor.py exited with code ${code}. Stderr: ${stderrData.trim() || 'No stderr output.'}`;
                console.error('Python script failed:', errorMessage);
                reject(new Error(errorMessage));
            }
        });
        py.on('error', (err) => {
            console.error('Error spawning Python process:', err);
            reject(err);
        });
    });
    try {
        console.log('Awaiting JSON result from Python script...');
        const jsonResultString = await jsonPromise;
        console.log('Received JSON string:', jsonResultString);
        const result = JSON.parse(jsonResultString);
        console.log('Parsed GradingResult:', result);
        return result;
    }
    catch (error) {
        return {
            pass: false,
            score: 0,
            reason: `Failed to execute or parse code: ${error.message || 'Unknown error during execution.'}`,
        };
    }
}
//# sourceMappingURL=codeJudge.js.map