<?php
require_once 'BaseAIService.php';

class ContentAnalysisService extends BaseAIService {

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

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

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

        $config = getAIConfig('content_analysis');
        if (strlen($data['content']) > $config['max_content_length']) {
            throw new Exception('Content exceeds maximum length limit');
        }

        return true;
    }

    /**
     * Analyze course content for readability, engagement, and learning objectives
     */
    public function analyzeContent($content, $analysisTypes = null) {
        $this->validateInput(['content' => $content]);

        $config = getAIConfig('content_analysis');
        $types = $analysisTypes ?? $config['analysis_types'];

        $prompt = $this->buildAnalysisPrompt($content, $types);

        $messages = [
            [
                'role' => 'system',
                'content' => 'You are an expert educational content analyst. Provide detailed, actionable analysis of learning content.'
            ],
            [
                'role' => 'user',
                'content' => $prompt
            ]
        ];

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

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

    private function buildAnalysisPrompt($content, $types) {
        $prompt = "Analyze the following educational content and provide feedback on:\n\n";

        foreach ($types as $type) {
            switch ($type) {
                case 'readability':
                    $prompt .= "- Readability: Assess reading level, complexity, and clarity\n";
                    break;
                case 'engagement':
                    $prompt .= "- Engagement: Evaluate how engaging and interesting the content is for learners\n";
                    break;
                case 'objectives_alignment':
                    $prompt .= "- Learning Objectives Alignment: Check if content aligns with stated learning goals\n";
                    break;
            }
        }

        $prompt .= "\nProvide specific suggestions for improvement.\n\nContent:\n{$content}";

        return $prompt;
    }

    private function parseAnalysisResponse($response) {
        // Parse the AI response into structured data
        // This would include readability score, engagement rating, etc.
        return [
            'readability_score' => $this->extractScore($response, 'readability'),
            'engagement_score' => $this->extractScore($response, 'engagement'),
            'objectives_alignment' => $this->extractScore($response, 'objectives'),
            'suggestions' => $this->extractSuggestions($response),
            'summary' => $this->extractSummary($response)
        ];
    }

    private function extractScore($response, $type) {
        // Simple regex extraction - could be improved with more sophisticated parsing
        $patterns = [
            'readability' => '/readability[^0-9]*([0-9]+(?:\.[0-9]+)?)/i',
            'engagement' => '/engagement[^0-9]*([0-9]+(?:\.[0-9]+)?)/i',
            'objectives' => '/objectives?[^0-9]*([0-9]+(?:\.[0-9]+)?)/i'
        ];

        if (isset($patterns[$type])) {
            preg_match($patterns[$type], $response, $matches);
            return isset($matches[1]) ? (float) $matches[1] : null;
        }

        return null;
    }

    private function extractSuggestions($response) {
        // Extract suggestions from the response
        $suggestions = [];
        if (preg_match_all('/suggestion[^:]*:?\s*(.*?)(?=\n\n|\n[A-Z]|$)/is', $response, $matches)) {
            $suggestions = array_map('trim', $matches[1]);
        }
        return $suggestions;
    }

    private function extractSummary($response) {
        // Extract summary/overview from response
        if (preg_match('/summary[^:]*:?\s*(.*?)(?=\n\n|\n[A-Z]|$)/is', $response, $match)) {
            return trim($match[1]);
        }
        return substr($response, 0, 200) . '...';
    }
}
?>