<?php
require_once 'BaseAIService.php';

class PerformanceAnalysisService extends BaseAIService {

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

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

    protected function validateInput($data) {
        if (!isset($data['performance_data']) || empty($data['performance_data'])) {
            throw new Exception('Performance data is required');
        }
        return true;
    }

    public function analyzePerformance($performanceData, $period = 'month') {
        $this->validateInput(['performance_data' => $performanceData]);

        $prompt = $this->buildAnalysisPrompt($performanceData, $period);

        $messages = [
            [
                'role' => 'system',
                'content' => 'You are an expert educational data analyst. Provide insights into student learning patterns and personalized recommendations.'
            ],
            [
                'role' => 'user',
                'content' => $prompt
            ]
        ];

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

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

    private function buildAnalysisPrompt($data, $period) {
        $prompt = "Analyze the following student performance data for the {$period} period.\n\n";
        $prompt .= "Performance Data:\n" . json_encode($data, JSON_PRETTY_PRINT) . "\n\n";
        $prompt .= "Provide:\n1. Learning pattern insights\n2. Strengths and weaknesses\n3. Personalized recommendations\n4. Progress trends\n5. Areas needing attention";

        return $prompt;
    }

    private function parseAnalysisResponse($response) {
        return [
            'insights' => $this->extractSection($response, 'insights'),
            'strengths' => $this->extractList($response, 'strengths'),
            'weaknesses' => $this->extractList($response, 'weaknesses'),
            'recommendations' => $this->extractList($response, 'recommendations'),
            'trends' => $this->extractSection($response, 'trends'),
            'focus_areas' => $this->extractList($response, 'focus')
        ];
    }

    private function extractSection($response, $section) {
        if (preg_match("/{$section}[^:]*:?\s*(.*?)(?=\n[A-Z]|\n\s*\d+\.|$)/is", $response, $match)) {
            return trim($match[1]);
        }
        return '';
    }

    private function extractList($response, $keyword) {
        $items = [];
        if (preg_match_all('/(?:^|\n)[•\-\*]\s*(.*?)(?=\n[•\-\*]|\n\n|$)/', $response, $matches)) {
            $items = $matches[1];
        }
        return $items;
    }
}
?>