"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.matchesOumiJudge = matchesOumiJudge;
const child_process_1 = require("child_process");
const fs = __importStar(require("fs"));
const path_1 = __importDefault(require("path"));
/**
 * Find the correct Python executable for the current platform
 */
function findPythonExecutable() {
    const isWindows = process.platform === 'win32';
    // Helper to find Python in PATH on Windows
    const findPythonInPath = (command) => {
        if (!isWindows) {
            return null;
        }
        const pathEnv = process.env.PATH || '';
        const paths = pathEnv.split(path_1.default.delimiter);
        for (const dir of paths) {
            const pythonPath = path_1.default.join(dir, `${command}.exe`);
            if (fs.existsSync(pythonPath)) {
                return pythonPath;
            }
        }
        return null;
    };
    // Try to find the correct Python executable
    const possiblePythonPaths = isWindows
        ? ['./venv/Scripts/python.exe', './venv/Scripts/python']
        : ['./venv/bin/python3', './venv/bin/python'];
    let pythonExecutable = null;
    // First, try venv paths (relative to project root)
    const projectRoot = path_1.default.resolve(__dirname, '../../..');
    for (const pythonPath of possiblePythonPaths) {
        const fullPath = path_1.default.join(projectRoot, pythonPath);
        if (fs.existsSync(fullPath)) {
            pythonExecutable = fullPath;
            break;
        }
    }
    // If not found in venv, try to find in system PATH
    if (!pythonExecutable) {
        if (isWindows) {
            pythonExecutable =
                findPythonInPath('python') || findPythonInPath('python3') || findPythonInPath('py');
        }
        else {
            // For Unix-like systems, try common locations
            const unixPaths = [
                '/usr/local/bin/python3.10',
                '/usr/bin/python3.10',
                '/usr/local/bin/python3',
                '/usr/bin/python3',
                '/usr/bin/python',
            ];
            for (const unixPath of unixPaths) {
                if (fs.existsSync(unixPath)) {
                    pythonExecutable = unixPath;
                    break;
                }
            }
        }
    }
    // Fallback to system command (will require shell mode)
    if (!pythonExecutable) {
        pythonExecutable = isWindows ? 'python' : 'python3';
    }
    return pythonExecutable;
}
/**
 * Calls the Python script oumi_judge.py to evaluate hallucination.
 */
async function matchesOumiJudge(prompt, answer, vars, assertion) {
    const backend = 'gpt4o';
    const pythonScriptPath = path_1.default.join(__dirname, 'python', 'oumi_judge.py');
    const pythonExecutable = findPythonExecutable();
    const needsShell = !path_1.default.isAbsolute(pythonExecutable);
    const jsonPromise = new Promise((resolve, reject) => {
        const pythonProcessArguments = [pythonScriptPath, backend, prompt, answer];
        const py = (0, child_process_1.spawn)(pythonExecutable, pythonProcessArguments, {
            env: process.env,
            shell: needsShell,
            windowsHide: true, // Hide console window on Windows
        });
        let out = '';
        let err = '';
        py.stdout.on('data', (chunk) => {
            const chunkStr = chunk.toString();
            out += chunkStr;
            console.log('Python stdout chunk:', chunkStr);
        });
        py.stderr.on('data', (chunk) => {
            const chunkStr = chunk.toString();
            err += chunkStr;
            console.error('Python stderr chunk:', chunkStr);
        });
        py.on('close', (code) => {
            console.log('Python process closed with code:', code);
            if (code === 0) {
                console.log('Python script succeeded. Output:', out);
                resolve(out);
            }
            else {
                const errorMessage = `oumi_judge.py exited with code ${code}. Stderr: ${err}`;
                console.error('Python script failed:', errorMessage);
                reject(new Error(errorMessage));
            }
        });
        py.on('error', (err) => {
            console.error('Error spawning Python process:', err);
            reject(err);
        });
    });
    try {
        const json = await jsonPromise;
        const result = JSON.parse(json);
        const pass = result.helpful && result.honest && result.safe;
        const gradingResult = {
            pass,
            score: result.score,
            reason: result.reason,
            namedScores: {
                helpful: result.helpful ? 1 : 0,
                honest: result.honest ? 1 : 0,
                safe: result.safe ? 1 : 0,
            },
            metadata: {
                helpful: result.helpful,
                honest: result.honest,
                safe: result.safe,
            },
        };
        return gradingResult;
    }
    catch (error) {
        console.error('Error processing JSON response:', error);
        return {
            pass: false,
            score: 0,
            reason: `Error: ${error.message}`,
            namedScores: {},
            metadata: {},
        };
    }
}
//# sourceMappingURL=matchesOumiJudge.js.map