<?php
require_once 'BaseAIService.php';

class EssayEvaluationService extends BaseAIService {

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

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

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

        if (!isset($data['question_content']) || empty($data['question_content'])) {
            throw new Exception('Question content is required for evaluation');
        }

        $config = getAIConfig('essay_evaluation');
        if (strlen($data['essay_content']) > $config['max_essay_length']) {
            throw new Exception('Essay content exceeds maximum length limit');
        }

        return true;
    }

    /**
     * Evaluate essay response with rubric-based scoring
     */
    public function evaluateEssay($essayContent, $questionContent, $rubric = null) {
        $this->validateInput([
            'essay_content' => $essayContent,
            'question_content' => $questionContent
        ]);

        $config = getAIConfig('essay_evaluation');
        $rubricTypes = $rubric ?? $config['rubric_types'];

        $prompt = $this->buildEvaluationPrompt($essayContent, $questionContent, $rubricTypes);

        $messages = [
            [
                'role' => 'system',
                'content' => 'You are an expert essay evaluator. Provide fair, detailed, and constructive feedback on student essays using established rubrics.'
            ],
            [
                'role' => 'user',
                'content' => $prompt
            ]
        ];

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

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

    private function buildEvaluationPrompt($essayContent, $questionContent, $rubricTypes) {
        $prompt = "Evaluate the following student essay response.\n\n";
        $prompt .= "Essay Question:\n{$questionContent}\n\n";
        $prompt .= "Student Essay:\n{$essayContent}\n\n";
        $prompt .= "Evaluation Criteria:\n";

        foreach ($rubricTypes as $type) {
            switch ($type) {
                case 'content':
                    $prompt .= "- Content: Accuracy, relevance, depth of understanding, use of evidence\n";
                    break;
                case 'structure':
                    $prompt .= "- Structure: Organization, coherence, logical flow, introduction/conclusion\n";
                    break;
                case 'grammar':
                    $prompt .= "- Grammar & Style: Clarity, grammar, vocabulary, writing mechanics\n";
                    break;
                case 'originality':
                    $prompt .= "- Originality: Critical thinking, unique insights, creativity\n";
                    break;
            }
        }

        $prompt .= "\nProvide:\n";
        $prompt .= "1. Overall score (0-100)\n";
        $prompt .= "2. Scores for each criterion (0-25 points each)\n";
        $prompt .= "3. Detailed feedback for each criterion\n";
        $prompt .= "4. Strengths and areas for improvement\n";
        $prompt .= "5. Suggestions for revision\n";
        $prompt .= "6. Final grade recommendation (A, B, C, D, F)";

        return $prompt;
    }

    private function parseEvaluationResponse($response) {
        $evaluation = [
            'overall_score' => 0,
            'criterion_scores' => [],
            'feedback' => [],
            'strengths' => [],
            'improvements' => [],
            'suggestions' => [],
            'grade' => '',
            'detailed_feedback' => ''
        ];

        // Extract overall score
        if (preg_match('/overall score[^0-9]*([0-9]+(?:\.[0-9]+)?)/i', $response, $match)) {
            $evaluation['overall_score'] = (float) $match[1];
        }

        // Extract criterion scores
        $criteria = ['content', 'structure', 'grammar', 'originality'];
        foreach ($criteria as $criterion) {
            if (preg_match("/{$criterion}[^0-9]*([0-9]+(?:\.[0-9]+)?)/i", $response, $match)) {
                $evaluation['criterion_scores'][$criterion] = (float) $match[1];
            }
        }

        // Extract grade
        if (preg_match('/grade[^A-F]*([A-F])/i', $response, $match)) {
            $evaluation['grade'] = $match[1];
        }

        // Extract feedback sections
        $sections = [
            'strengths' => '/strengths?:?\s*(.*?)(?=\n[A-Z]|\n\s*\d+\.|$)/is',
            'improvements' => '/(?:areas? for )?improvements?:?\s*(.*?)(?=\n[A-Z]|\n\s*\d+\.|$)/is',
            'suggestions' => '/suggestions?:?\s*(.*?)(?=\n[A-Z]|\n\s*\d+\.|$)/is'
        ];

        foreach ($sections as $key => $pattern) {
            if (preg_match($pattern, $response, $match)) {
                $content = trim($match[1]);
                $evaluation[$key] = array_filter(array_map('trim', preg_split('/\n+/', $content)));
            }
        }

        // Store full response as detailed feedback
        $evaluation['detailed_feedback'] = $response;

        return $evaluation;
    }

    /**
     * Batch evaluate multiple essays
     */
    public function batchEvaluateEssays($essays, $questionContent) {
        $results = [];

        foreach ($essays as $essay) {
            try {
                $results[] = [
                    'essay_id' => $essay['id'] ?? null,
                    'evaluation' => $this->evaluateEssay($essay['content'], $questionContent),
                    'status' => 'success'
                ];
            } catch (Exception $e) {
                $results[] = [
                    'essay_id' => $essay['id'] ?? null,
                    'error' => $e->getMessage(),
                    'status' => 'error'
                ];
            }
        }

        return $results;
    }
}
?>