<?php

require_once __DIR__ . '/exam_utils.php';
require_once dirname(__DIR__, 2) . '/ai_config.php';

function quoteCommandIfNeeded($command) {
    return str_contains($command, ' ') ? '"' . $command . '"' : $command;
}

function resolvePythonCommand() {
    $candidates = [
        'C:\\Users\\Richard Korankye\\AppData\\Local\\Python\\bin\\python.exe',
        'python',
        'py -3',
        'py',
        'C:\\Python313\\python.exe',
        'C:\\Python312\\python.exe',
        'C:\\Program Files\\Python313\\python.exe',
        'C:\\Program Files\\Python312\\python.exe',
        'C:\\Users\\Richard Korankye\\AppData\\Local\\Programs\\Python\\Python313\\python.exe',
        'C:\\Users\\Richard Korankye\\AppData\\Local\\Programs\\Python\\Python312\\python.exe'
    ];

    foreach ($candidates as $candidate) {
        $output = [];
        $status = 1;
        $probe = quoteCommandIfNeeded($candidate) . ' --version 2>&1';
        @exec($probe, $output, $status);
        if ($status === 0) {
            return $candidate;
        }
    }

    return null;
}

function buildPythonPayload(array $requestData, array $materials) {
    return [
        'class_name' => $requestData['class_name'],
        'subject_id' => (int) $requestData['subject_id'],
        'subject_name' => $requestData['subject_name'],
        'term' => $requestData['term'],
        'exam_title' => $requestData['exam_title'],
        'duration' => (int) $requestData['duration'],
        'total_marks' => (int) $requestData['total_marks'],
        'exam_type' => $requestData['exam_type'],
        'include_objective' => $requestData['include_objective'] === 'true',
        'include_subjective' => $requestData['include_subjective'] === 'true',
        'include_comprehension' => $requestData['include_comprehension'] === 'true',
        'obj_count' => (int) $requestData['obj_count'],
        'obj_marks' => (int) $requestData['obj_marks'],
        'subj_count' => (int) $requestData['subj_count'],
        'subj_marks' => (int) $requestData['subj_marks'],
        'ai_notes' => trim((string) ($requestData['ai_notes'] ?? '')),
        'topics' => trim((string) ($requestData['topics'] ?? '')),
        'sample_questions' => trim((string) ($requestData['sample_questions'] ?? '')),
        'subject_rules' => $requestData['subject_rules'] ?? [],
        'retrieval_context' => $requestData['retrieval_context'] ?? [],
        'materials' => array_map(function ($material) {
            return [
                'id' => (int) $material['id'],
                'title' => $material['title'],
                'material_type' => $material['material_type'],
                'content' => $material['content'] ?? '',
                'content_preview' => $material['content_preview'] ?? ''
            ];
        }, $materials),
        'openai_api_key' => defined('AI_OPENAI_API_KEY') ? AI_OPENAI_API_KEY : '',
        'model' => 'gpt-4o-mini'
    ];
}

function generateExamUsingPython(array $requestData, array $materials) {
    $python = resolvePythonCommand();
    if (!$python) {
        return ['success' => false, 'message' => 'Python runtime not found on the server.'];
    }

    $scriptPath = realpath(dirname(__DIR__) . '/python_exam_generator.py');
    if (!$scriptPath) {
        return ['success' => false, 'message' => 'Python generator script not found.'];
    }

    $payload = buildPythonPayload($requestData, $materials);
    $descriptors = [0 => ['pipe', 'r'], 1 => ['pipe', 'w'], 2 => ['pipe', 'w']];
    $pythonCommand = quoteCommandIfNeeded($python);
    $process = @proc_open($pythonCommand . ' ' . escapeshellarg($scriptPath), $descriptors, $pipes, dirname(__DIR__));
    if (!is_resource($process)) {
        return ['success' => false, 'message' => 'Failed to start the Python exam generator.'];
    }

    fwrite($pipes[0], json_encode($payload, JSON_UNESCAPED_UNICODE));
    fclose($pipes[0]);
    $stdout = stream_get_contents($pipes[1]);
    fclose($pipes[1]);
    $stderr = stream_get_contents($pipes[2]);
    fclose($pipes[2]);

    $status = proc_close($process);
    if ($status !== 0) {
        return ['success' => false, 'message' => trim($stderr) ?: 'Python generator failed.'];
    }

    $decoded = json_decode($stdout, true);
    if (!is_array($decoded) || empty($decoded['success']) || !isset($decoded['exam'])) {
        return ['success' => false, 'message' => 'Python generator returned invalid data.', 'raw' => $stdout];
    }

    $decoded['exam'] = normalizeExamData($decoded['exam'], $requestData);
    return $decoded;
}

