<?php

namespace App\Http\Controllers\Client;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\AiChat;
use App\Models\AiMessage;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Exception;

class AiChatController extends Controller
{
    public function index()
    {
        // Create or get the single chat thread for this user
        $chat = AiChat::firstOrCreate(
            ['user_id' => Auth::id()],
            ['title' => 'Legal Assistant']
        );

        $messages = $chat->messages()->oldest()->get();

        // Ensure this view exists!
        return view('admin.clients.chat.index', compact('chat', 'messages'));
    }

    public function sendMessage(Request $request)
    {
        $request->validate(['message' => 'required|string']);

        $chat = AiChat::where('user_id', Auth::id())->firstOrFail();

        // 1. Save User Message
        $chat->messages()->create([
            'role' => 'user',
            'content' => $request->message
        ]);

        // 2. Prepare Prompt
        // Note: AI models cannot "read" PDF links directly unless they have browsing tools.
        // It is better to rely on their internal knowledge of the 2010 Constitution.
        $systemPrompt = "You are a helpful Kenyan legal assistant. Base your answers on the Constitution of Kenya 2010 https://www.parliament.go.ke/sites/default/files/2017-05/The_Constitution_of_Kenya_2010.pdf. User Query: " . $request->message;

        // 3. Get Response (With Fallback Chain)
        $aiResponseText = $this->getAiResponse($systemPrompt);

        // 4. Save AI Message
        $chat->messages()->create([
            'role' => 'assistant',
            'content' => $aiResponseText
        ]);

        return response()->json(['status' => 'success', 'reply' => $aiResponseText]);
    }

    /**
     * The Master Logic: Tries Gemini Keys 1-3 -> OpenAI -> Ollama
     */
    private function getAiResponse($prompt)
    {
        set_time_limit(120);

        // --- ATTEMPT 1: GEMINI KEY 1 ---
        try {
            $text = $this->callGemini($prompt, 'services.gemini.key');
            if ($text) return $text;
        } catch (Exception $e) {
            Log::warning('Gemini 1 Error: ' . $e->getMessage());
        }

        // --- ATTEMPT 2: GEMINI KEY 2 ---
        try {
            $text = $this->callGemini($prompt, 'services.gemini_2.key');
            if ($text) return $text;
        } catch (Exception $e) {
            Log::warning('Gemini 2 Error: ' . $e->getMessage());
        }

        // --- ATTEMPT 3: GEMINI KEY 3 ---
        try {
            $text = $this->callGemini($prompt, 'services.gemini_3.key');
            if ($text) return $text;
        } catch (Exception $e) {
            Log::warning('Gemini 3 Error: ' . $e->getMessage());
        }

        // --- ATTEMPT 4: OPENAI ---
        try {
            $text = $this->callOpenAI($prompt);
            if ($text) return $text;
        } catch (Exception $e) {
            Log::warning('OpenAI Error: ' . $e->getMessage());
        }

        // --- ATTEMPT 5: OLLAMA (Local) ---
        try {
            $text = $this->callOllama($prompt);
            if ($text) return $text . "\n\n(Generated via Local AI)";
        } catch (Exception $e) {
            Log::error('Ollama Error: ' . $e->getMessage());
        }

        return "I apologize, but I am currently unable to connect to the legal server. Please contact the firm directly.";
    }

    // --- HELPER FUNCTIONS ---

    // Combined Gemini function to handle multiple keys easily
    private function callGemini($prompt, $configKey)
    {
        $apiKey = config($configKey);

        if (!$apiKey) return null; // Skip if key not set

        $response = Http::withOptions(['verify' => false, 'timeout' => 15])
            ->withHeaders(['Content-Type' => 'application/json'])
            ->post("https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key={$apiKey}", [
                'contents' => [['role' => 'user', 'parts' => [['text' => $prompt]]]],
                'generationConfig' => ['temperature' => 0.3, 'maxOutputTokens' => 10000]
            ]);

        if ($response->successful()) {
            return $response->json()['candidates'][0]['content']['parts'][0]['text'] ?? null;
        }

        Log::warning("Gemini ($configKey) Failed: " . $response->body());
        return null;
    }

    private function callOpenAI($prompt)
    {
        $apiKey = config('services.openai.key');
        if (!$apiKey) return null;

        $response = Http::withOptions(['verify' => false, 'timeout' => 15])
            ->withToken($apiKey)
            ->post("https://api.openai.com/v1/chat/completions", [
                'model' => 'gpt-4o-mini',
                'messages' => [['role' => 'user', 'content' => $prompt]],
                'temperature' => 0.3
            ]);

        if ($response->successful()) {
            return $response->json()['choices'][0]['message']['content'] ?? null;
        }
        return null;
    }

    private function callOllama($prompt)
    {
        // Use 127.0.0.1 to avoid localhost ipv6 issues
        $url = "http://127.0.0.1:11434/api/chat";

        $response = Http::withOptions(['verify' => false, 'timeout' => 60])
            ->post($url, [
                'model' => env('OLLAMA_MODEL', 'llama3'),
                'messages' => [['role' => 'user', 'content' => $prompt]],
                'stream' => false,
            ]);

        if ($response->successful()) {
            return $response->json()['message']['content'] ?? null;
        }
        return null;
    }
}
