<?php
require_once 'BaseAIService.php';

class ContentSummarizationService extends BaseAIService {

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

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

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

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

        return true;
    }

    public function summarizeContent($content, $length = 'medium', $focus = null) {
        $this->validateInput(['content' => $content]);

        $prompt = $this->buildSummarizationPrompt($content, $length, $focus);

        $messages = [
            [
                'role' => 'system',
                'content' => 'You are an expert at creating concise, accurate summaries of educational content.'
            ],
            [
                'role' => 'user',
                'content' => $prompt
            ]
        ];

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

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

    private function buildSummarizationPrompt($content, $length, $focus) {
        $lengthGuide = [
            'short' => '1-2 paragraphs, key points only',
            'medium' => '3-4 paragraphs, main concepts and examples',
            'long' => 'detailed summary with subsections'
        ];

        $prompt = "Summarize the following educational content.\n\n";
        $prompt .= "Summary Length: {$lengthGuide[$length]}\n";

        if ($focus) {
            $prompt .= "Focus Area: {$focus}\n";
        }

        $prompt .= "\nContent:\n{$content}\n\n";
        $prompt .= "Provide a clear, structured summary that captures the essential information.";

        return $prompt;
    }

    private function parseSummaryResponse($response) {
        return [
            'summary' => trim($response),
            'word_count' => str_word_count($response),
            'key_points' => $this->extractKeyPoints($response)
        ];
    }

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