<?php
namespace App\Services;

class AiService {
    private $pdo;
    private $provider = null;
    private $error = '';

    public function __construct(\PDO $pdo) {
        $this->pdo = $pdo;
        $this->loadProvider();
    }

    private function loadProvider(): void {
        try {
            $this->provider = $this->pdo->query("SELECT * FROM ai_providers WHERE is_active = 1 AND is_default = 1 LIMIT 1")->fetch();
            if (!$this->provider) {
                $this->provider = $this->pdo->query("SELECT * FROM ai_providers WHERE is_active = 1 LIMIT 1")->fetch();
            }
        } catch (\PDOException $e) {
            $this->error = 'Failed to load AI provider: ' . $e->getMessage();
        }
    }

    public function isEnabled(): bool {
        return $this->provider !== null && !empty($this->provider['api_key_encrypted']);
    }

    private function callApi(string $prompt, int $maxTokens = 1000, float $temperature = 0.7): ?string {
        if (!$this->isEnabled()) {
            $this->error = 'AI is not configured or disabled';
            return null;
        }

        $url = rtrim($this->provider['base_url'], '/') . '/chat/completions';
        $payload = json_encode([
            'model' => $this->provider['model'],
            'messages' => [['role' => 'user', 'content' => $prompt]],
            'max_tokens' => $maxTokens,
            'temperature' => $temperature,
        ]);

        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => $payload,
            CURLOPT_HTTPHEADER => [
                'Content-Type: application/json',
                'Authorization: Bearer ' . $this->provider['api_key_encrypted'],
            ],
            CURLOPT_TIMEOUT => 60,
            CURLOPT_SSL_VERIFYPEER => true,
        ]);

        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($httpCode !== 200 || !$response) {
            $this->error = 'AI API call failed (HTTP ' . $httpCode . ')';
            $this->logUsage('api_call', $prompt, '', 0, false, $this->error);
            return null;
        }

        $data = json_decode($response, true);
        $content = $data['choices'][0]['message']['content'] ?? '';
        $tokensUsed = $data['usage']['total_tokens'] ?? 0;

        $this->logUsage('api_call', $prompt, $content, $tokensUsed, true);
        return $content;
    }

    public function generateQuestionVariations(int $questionId, int $count = 3): array {
        $stmt = $this->pdo->prepare("SELECT question_text, explanation, difficulty, question_type FROM questions WHERE id = ?");
        $stmt->execute([$questionId]);
        $question = $stmt->fetch();
        if (!$question) return [];

        $prompt = "Generate {$count} variations of this {$question['difficulty']} level {$question['question_type']} question. Keep the same learning outcome and difficulty level. Only change the wording and context.\n\nOriginal: {$question['question_text']}\n\nReturn only a JSON array of strings, no explanation.";
        $result = $this->callApi($prompt, 1500, 0.8);
        if (!$result) return [];

        $variations = json_decode($result, true);
        if (!is_array($variations)) {
            $variations = array_filter(explode("\n", $result), function($line) { return strlen(trim($line)) > 10; });
        }

        foreach ($variations as $v) {
            $this->pdo->prepare("INSERT INTO questions (bank_id, question_type, question_text, explanation, difficulty, points, ai_generated, parent_question_id) SELECT bank_id, question_type, ?, explanation, difficulty, points, 1, id FROM questions WHERE id = ?")
                ->execute([trim($v, '" '), $questionId]);
        }

        return array_slice($variations, 0, $count);
    }

    public function generateStudyRecommendations(int $studentId): string {
        $stmt = $this->pdo->prepare("SELECT ta.score, t.title as test_title, c.title as course_title, ta.passed FROM test_attempts ta JOIN tests t ON ta.test_id = t.id JOIN courses c ON t.course_id = c.id JOIN enrollments e ON c.id = e.course_id WHERE ta.student_id = ? AND ta.status = 'completed' ORDER BY ta.ended_at DESC LIMIT 10");
        $stmt->execute([$studentId]);
        $results = $stmt->fetchAll();

        if (empty($results)) return 'No test data available for recommendations.';

        $data = "Student test history:\n";
        foreach ($results as $r) {
            $data .= "- {$r['test_title']} ({$r['course_title']}): {$r['score']}% - " . ($r['passed'] ? 'Passed' : 'Failed') . "\n";
        }

        $prompt = "Based on these test results, provide 3-5 specific study recommendations for this student. Focus on areas of weakness and suggest specific topics to review.\n\n{$data}\n\nProvide practical, actionable advice. Keep response under 300 words.";
        return $this->callApi($prompt, 800, 0.7) ?? 'AI recommendations unavailable. Please review your test results manually.';
    }

    public function generatePerformanceSummary(int $studentId): string {
        $stmt = $this->pdo->prepare("SELECT s.student_number, u.first_name, u.last_name, (SELECT COUNT(*) FROM enrollments WHERE student_id = s.id AND status = 'active') as active_courses, (SELECT COUNT(*) FROM test_attempts WHERE student_id = s.id AND status = 'completed') as tests_taken, (SELECT COUNT(*) FROM test_attempts WHERE student_id = s.id AND status = 'completed' AND passed = 1) as tests_passed, (SELECT AVG(score) FROM test_attempts WHERE student_id = s.id AND status = 'completed') as avg_score FROM students s JOIN users u ON s.user_id = u.id WHERE s.id = ?");
        $stmt->execute([$studentId]);
        $s = $stmt->fetch();
        if (!$s) return '';

        $prompt = "Write a professional student performance narrative for {$s['first_name']} {$s['last_name']} ({$s['student_number']}). Active courses: {$s['active_courses']}, Tests taken: {$s['tests_taken']}, Tests passed: {$s['tests_passed']}, Average score: " . round($s['avg_score'] ?? 0, 1) . "%. Write 2-3 paragraphs suitable for an academic report. Be encouraging but honest about areas for improvement.";
        return $this->callApi($prompt, 600, 0.7) ?? "Student {$s['first_name']} {$s['last_name']} has completed {$s['tests_taken']} tests with an average score of " . round($s['avg_score'] ?? 0, 1) . "%.";
    }

    public function generateQuestionFromTopic(string $topic, string $type = 'multiple_choice', string $difficulty = 'medium'): ?array {
        $prompt = "Generate a {$difficulty} level {$type} question about \"{$topic}\". Return JSON with: {\"question_text\": \"...\", \"options\": [\"A\", \"B\", \"C\", \"D\"], \"correct_index\": 0, \"explanation\": \"...\"}";
        $result = $this->callApi($prompt, 500, 0.6);
        if (!$result) return null;

        $data = json_decode($result, true);
        if (!$data || !isset($data['question_text'])) return null;
        return $data;
    }

    public function rephraseQuestion(int $questionId): ?string {
        $stmt = $this->pdo->prepare("SELECT question_text FROM questions WHERE id = ?");
        $stmt->execute([$questionId]);
        $text = $stmt->fetchColumn();
        if (!$text) return null;

        $prompt = "Rephrase this question to use different wording while keeping the exact same meaning, difficulty level, and correct answer logic. Return only the rephrased question text, nothing else.\n\nOriginal: {$text}";
        return $this->callApi($prompt, 300, 0.5);
    }

    public function generateQuizFromLesson(int $lessonId, int $questionCount = 5): array {
        $stmt = $this->pdo->prepare("SELECT l.title, l.content, m.title as module_title, c.title as course_title FROM lessons l JOIN modules m ON l.module_id = m.id JOIN courses c ON m.course_id = c.id WHERE l.id = ?");
        $stmt->execute([$lessonId]);
        $lesson = $stmt->fetch();
        if (!$lesson) return [];

        $content = strip_tags(substr($lesson['content'] ?? '', 0, 2000));
        $prompt = "Based on this lesson content, generate {$questionCount} multiple choice quiz questions with 4 options each. Return JSON array: [{\"question\": \"...\", \"options\": [\"A\", \"B\", \"C\", \"D\"], \"correct\": 0, \"explanation\": \"...\"}]\n\nLesson: {$lesson['title']}\nContent: {$content}";
        $result = $this->callApi($prompt, 2000, 0.6);
        if (!$result) return [];

        $questions = json_decode($result, true);
        return is_array($questions) ? $questions : [];
    }

    private function logUsage(string $feature, string $prompt, string $response, int $tokens, bool $success, string $error = '') {
        try {
            $this->pdo->prepare("INSERT INTO ai_logs (provider_id, feature, prompt_text, response_text, tokens_used, success, error_message) VALUES (?, ?, ?, ?, ?, ?, ?)")
                ->execute([$this->provider['id'] ?? null, $feature, substr($prompt, 0, 5000), substr($response, 0, 10000), $tokens, $success ? 1 : 0, $error]);
        } catch (\Exception $e) {
            error_log("[AiService] Log failed: " . $e->getMessage());
        }
    }

    public function getError(): string { return $this->error; }
    public function getProvider(): ?array { return $this->provider; }
    public function getProviders(): array { return $this->pdo->query("SELECT id, name, model, is_active, is_default FROM ai_providers ORDER BY name")->fetchAll(); }
    public function getLogs(int $limit = 50): array {
        $stmt = $this->pdo->prepare("SELECT al.*, ap.name as provider_name FROM ai_logs al LEFT JOIN ai_providers ap ON al.provider_id = ap.id ORDER BY al.created_at DESC LIMIT ?");
        $stmt->execute([$limit]);
        return $stmt->fetchAll();
    }
}
