<?php
namespace Peak;

class ChatAI {
    public static function handleRequest(): void {
        $data = Request::json();
        $message = $data['message'] ?? '';
        $history = $data['history'] ?? [];
        $training = $data['training'] ?? null;
        $sysPrompt = 'You are Peak AI, an intelligent assistant for the Peak workflow platform.';
        $model = 'groq-compound';
        $temperature = 0.7;
        $maxTokens = 1024;
        $knowledge = '';

        if ($training) {
            $sysPrompt = $training['system_prompt'] ?? $sysPrompt;
            $model = $training['model'] ?? $model;
            $temperature = $training['temperature'] ?? $temperature;
            $maxTokens = $training['max_tokens'] ?? $maxTokens;
            $knowledge = $training['knowledge'] ?? '';
        } else {
            try {
                $rows = Database::fetchAll('SELECT setting_key, setting_value FROM settings WHERE setting_key IN (?, ?, ?, ?, ?)',
                    ['ai_system_prompt', 'ai_model', 'ai_temperature', 'ai_max_tokens', 'ai_knowledge']);
                foreach ($rows as $r) {
                    switch ($r['setting_key']) {
                        case 'ai_system_prompt': $sysPrompt = $r['setting_value']; break;
                        case 'ai_model': $model = $r['setting_value']; break;
                        case 'ai_temperature': $temperature = (float)$r['setting_value'] ?: 0.7; break;
                        case 'ai_max_tokens': $maxTokens = (int)$r['setting_value'] ?: 1024; break;
                        case 'ai_knowledge': $knowledge = $r['setting_value']; break;
                    }
                }
            } catch (\Throwable) {}
        }
        if ($knowledge) $sysPrompt .= "\n\nPlatform knowledge:\n" . $knowledge;
        $messages = [['role' => 'system', 'content' => $sysPrompt]];
        foreach ($history as $h) $messages[] = ['role' => $h['role'], 'content' => $h['content']];
        $messages[] = ['role' => 'user', 'content' => $message];
        Response::json(['reply' => self::callAI($model, $messages, $temperature, $maxTokens)]);
    }

    private static function isGeminiModel(string $model): bool {
        return strpos($model, 'gemini') === 0 || strpos($model, 'gemma') === 0;
    }

    private static function resolveGeminiModel(string $model): string {
        $map = [
            'gemini-3.5-flash' => 'gemini-3.5-flash',
            'gemini-3.1-pro' => 'gemini-3.1-pro-preview',
            'gemini-3.1-flash-lite' => 'gemini-3.1-flash-lite',
            'gemini-3-flash' => 'gemini-3-flash-preview',
            'gemini-3-flash-live' => 'gemini-3-flash-preview',
            'gemini-3' => 'gemini-3-pro-preview',
            'gemini-2.5-pro' => 'gemini-2.5-pro',
            'gemini-2.5-flash' => 'gemini-2.5-flash',
            'gemini-2.5-flash-lite' => 'gemini-2.5-flash-lite',
            'gemini-2.5-flash-tts' => 'gemini-2.5-flash-preview-tts',
            'gemini-2.5-pro-tts' => 'gemini-2.5-pro-preview-tts',
            'gemini-2.5-flash-native-audio' => 'gemini-2.5-flash',
            'gemini-2-flash' => 'gemini-2.0-flash',
            'gemini-2-flash-lite' => 'gemini-2.0-flash-lite',
            'gemini-2.5' => 'gemini-2.5-pro',
            'gemini-2' => 'gemini-2.0-pro',
            'gemma-4-31b' => 'gemma-4-31b-it',
            'gemma-4-26b' => 'gemma-4-26b-it',
        ];
        return $map[$model] ?? $model;
    }

    private static function resolveModel(string $model): string {
        $map = [
            'groq-compound' => 'llama-3.3-70b-versatile',
            'llama-3.3-70b-versatile' => 'llama-3.3-70b-versatile',
            'mixtral-8x7b-32768' => 'mixtral-8x7b-32768',
            'llama-guard-3-8b' => 'llama-guard-3-8b',
            'gemma2-9b-it' => 'gemma2-9b-it'
        ];
        return $map[$model] ?? 'llama-3.3-70b-versatile';
    }

    private static function fallbackReply(string $msg): string {
        $q = mb_strtolower($msg);
        if (strpos($q, 'hello') !== false || strpos($q, 'hi') !== false || strpos($q, 'hey') !== false) return 'Hello! How can I help you with your Peak platform today?';
        if (strpos($q, 'workflow') !== false) return 'You can manage workflows in the Workflows tab. Click "Add Workflow" to create a new one, or manage existing ones.';
        if (strpos($q, 'setting') !== false || strpos($q, 'config') !== false) return 'Head to the Settings tab to update your profile, notification preferences, appearance theme, and account security options.';
        if (strpos($q, 'theme') !== false) return 'You can switch between Dark, Light, or System themes in Settings > Appearance.';
        if (strpos($q, 'profile') !== false) return 'Your profile contains your name, email, and role. Update them in Settings > Profile.';
        if (strpos($q, 'who are you') !== false) return 'I am Peak AI, your intelligent assistant for the Peak workflow platform.';
        if (strpos($q, 'help') !== false || strpos($q, 'what can you') !== false) return "I can help you with:\n• Managing workflows\n• Configuring platform settings\n• Explaining features\n• Answering questions about Peak\n\nJust ask me anything!";
        return 'I understand you\'re asking about "' . mb_substr($msg, 0, 50) . '". To get the best answer, try asking about workflows, settings, profile, or themes.';
    }

    private static function callAI(string $model, array $messages, float $temperature, int $maxTokens): string {
        if (self::isGeminiModel($model)) {
            return self::callGemini($model, $messages, $temperature, $maxTokens);
        }
        $apiModel = self::resolveModel($model);
        $body = json_encode([
            'model' => $apiModel,
            'messages' => $messages,
            'temperature' => $temperature,
            'max_tokens' => $maxTokens
        ]);
        $ch = curl_init('https://api.groq.com/openai/v1/chat/completions');
        curl_setopt_array($ch, [
            CURLOPT_POST => true,
            CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . Config::$GROQ_API_KEY, 'Content-Type: application/json'],
            CURLOPT_POSTFIELDS => $body,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_MAXREDIRS => 3
        ]);
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        if ($httpCode < 200 || $httpCode >= 300) return self::fallbackReply($messages[count($messages) - 1]['content']);
        $parsed = json_decode($response, true);
        if ($parsed && isset($parsed['choices'][0]['message']['content'])) return $parsed['choices'][0]['message']['content'];
        return self::fallbackReply($messages[count($messages) - 1]['content']);
    }

    private static function callGemini(string $model, array $messages, float $temperature, int $maxTokens): string {
        $apiModel = self::resolveGeminiModel($model);
        $url = 'https://generativelanguage.googleapis.com/v1beta/models/' . $apiModel . ':generateContent?key=' . Config::$GEMINI_API_KEY;
        $sysMsg = '';
        $geminiContents = [];
        foreach ($messages as $m) {
            if ($m['role'] === 'system') {
                $sysMsg = $m['content'];
            } else {
                $role = $m['role'] === 'assistant' ? 'model' : 'user';
                $geminiContents[] = ['role' => $role, 'parts' => [['text' => $m['content']]]];
            }
        }
        $payload = ['contents' => $geminiContents, 'generationConfig' => ['temperature' => $temperature, 'maxOutputTokens' => $maxTokens]];
        if ($sysMsg) $payload['systemInstruction'] = ['parts' => [['text' => $sysMsg]]];
        $body = json_encode($payload);
        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_POST => true,
            CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
            CURLOPT_POSTFIELDS => $body,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 60,
            CURLOPT_SSL_VERIFYPEER => false,
        ]);
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        if ($httpCode < 200 || $httpCode >= 300) return self::fallbackReply($messages[count($messages) - 1]['content']);
        $parsed = json_decode($response, true);
        if ($parsed && isset($parsed['candidates'][0]['content']['parts'][0]['text'])) {
            return $parsed['candidates'][0]['content']['parts'][0]['text'];
        }
        return self::fallbackReply($messages[count($messages) - 1]['content']);
    }
}
