<?php
require_once 'BaseAIService.php';

class QuestionGenerationService extends BaseAIService {

    protected function isFeatureEnabled() {
        return isAIFeatureEnabled('question_generation');
    }

    protected function getFeatureName() {
        return 'question_generation';
    }

    protected function validateInput($data) {
        if (!isset($data['content']) || empty($data['content'])) {
            throw new Exception('Content is required for question generation');
        }

        if (!isset($data['question_types']) || empty($data['question_types'])) {
            throw new Exception('Question types are required');
        }

        $config = getAIConfig('question_generation');
        $validTypes = $config['supported_types'];

        foreach ($data['question_types'] as $type) {
            if (!in_array($type, $validTypes)) {
                throw new Exception("Unsupported question type: {$type}");
            }
        }

        if (isset($data['count']) && $data['count'] > $config['max_questions_per_request']) {
            throw new Exception('Requested question count exceeds limit');
        }

        return true;
    }

    /**
     * Generate questions based on lesson content
     */
    public function generateQuestions($content, $questionTypes, $count = 5, $difficulty = 'medium') {
        $this->validateInput([
            'content' => $content,
            'question_types' => $questionTypes,
            'count' => $count
        ]);

        $prompt = $this->buildQuestionPrompt($content, $questionTypes, $count, $difficulty);

        $messages = [
            [
                'role' => 'system',
                'content' => 'You are an expert question writer for educational assessments. Create high-quality, pedagogically sound questions.'
            ],
            [
                'role' => 'user',
                'content' => $prompt
            ]
        ];

        $response = $this->makeRequest($messages);

        return $this->parseQuestionResponse($response->choices[0]->message->content, $questionTypes);
    }

    private function buildQuestionPrompt($content, $questionTypes, $count, $difficulty) {
        $typeDescriptions = [
            'mcq_single' => 'Multiple Choice (Single Answer): 4 options, one correct',
            'mcq_multiple' => 'Multiple Choice (Multiple Answers): 4-5 options, multiple correct',
            'true_false' => 'True/False questions',
            'short_answer' => 'Short answer questions (1-3 sentences)',
            'essay' => 'Essay questions requiring detailed responses'
        ];

        $prompt = "Generate {$count} assessment questions based on the following content.\n\n";
        $prompt .= "Question Types: " . implode(', ', array_map(function($type) use ($typeDescriptions) {
            return $typeDescriptions[$type] ?? $type;
        }, $questionTypes)) . "\n\n";
        $prompt .= "Difficulty Level: {$difficulty}\n\n";
        $prompt .= "Requirements:\n";
        $prompt .= "- Questions should test understanding of key concepts\n";
        $prompt .= "- Include correct answers and explanations\n";
        $prompt .= "- For MCQ, provide plausible distractors\n";
        $prompt .= "- Ensure questions align with Bloom's taxonomy\n\n";
        $prompt .= "Content:\n{$content}\n\n";
        $prompt .= "Format each question with type, question text, options (if applicable), correct answer, and explanation.";

        return $prompt;
    }

    private function parseQuestionResponse($response, $questionTypes) {
        $questions = [];

        // Split response into individual questions
        $questionBlocks = preg_split('/\n\s*\n(?=Question\s+\d+:|Type:)/i', $response);

        foreach ($questionBlocks as $block) {
            if (empty(trim($block))) continue;

            $question = $this->parseQuestionBlock($block);
            if ($question) {
                $questions[] = $question;
            }
        }

        return $questions;
    }

    private function parseQuestionBlock($block) {
        $question = [
            'title' => '',
            'content' => '',
            'question_type' => '',
            'difficulty' => 'medium',
            'points' => 1,
            'options' => [],
            'explanation' => '',
            'hints' => []
        ];

        // Extract question type
        if (preg_match('/Type:\s*([a-z_]+)/i', $block, $match)) {
            $question['question_type'] = $match[1];
        }

        // Extract question content
        if (preg_match('/Question:\s*(.*?)(?=\nOptions:|\nAnswer:|\nExplanation:|$)/is', $block, $match)) {
            $question['content'] = trim($match[1]);
            $question['title'] = substr($question['content'], 0, 100) . '...';
        }

        // Extract options for MCQ
        if (preg_match('/Options:\s*(.*?)(?=\nAnswer:|\nExplanation:|$)/is', $block, $match)) {
            $optionsText = $match[1];
            $optionLines = preg_split('/\n/', $optionsText);
            $options = [];

            foreach ($optionLines as $line) {
                if (preg_match('/^[A-D]\)\s*(.*)/', $line, $optMatch)) {
                    $options[] = [
                        'text' => trim($optMatch[1]),
                        'is_correct' => false // Will be set based on answer
                    ];
                }
            }

            $question['options'] = $options;
        }

        // Extract correct answer
        if (preg_match('/Answer:\s*(.*?)(?=\nExplanation:|$)/is', $block, $match)) {
            $answer = trim($match[1]);

            if ($question['question_type'] === 'mcq_single' || $question['question_type'] === 'mcq_multiple') {
                // Mark correct options
                $correctLetters = str_split(preg_replace('/[^A-D]/', '', $answer));
                foreach ($correctLetters as $letter) {
                    $index = ord($letter) - ord('A');
                    if (isset($question['options'][$index])) {
                        $question['options'][$index]['is_correct'] = true;
                    }
                }
            } else {
                // For other types, store the answer directly
                $question['correct_answer'] = $answer;
            }
        }

        // Extract explanation
        if (preg_match('/Explanation:\s*(.*?)$/is', $block, $match)) {
            $question['explanation'] = trim($match[1]);
        }

        return $question;
    }
}
?>