<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\LegalCase;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Http;
use Exception;

class AiController extends Controller
{
    public function generateAnalysis(LegalCase $case)
    {
        set_time_limit(120); // Allow 2 minutes for processing

        $context = $this->prepareContext($case);
        $prompt = $this->preparePrompt($context);

        // --- STEP 1: TRY GOOGLE GEMINI (Keys 1, 2, & 3) ---
        // We loop through keys to avoid repeating code
        $geminiKeys = [
            'services.gemini.key',
            'services.gemini_2.key',
            'services.gemini_3.key'
        ];

        foreach ($geminiKeys as $index => $configKey) {
            try {
                $response = $this->callGemini($prompt, $configKey);

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

                    if ($text) {
                        return $this->saveAndRedirect($case, $text, 'Gemini (Key ' . ($index + 1) . ')');
                    }
                }
                // Log warning but continue loop
                Log::warning("Gemini Key " . ($index + 1) . " Failed: " . $response->body());
            } catch (Exception $e) {
                Log::warning("Gemini Key " . ($index + 1) . " Error: " . $e->getMessage());
            }
        }

        // --- STEP 2: TRY OPENAI (Backup) ---
        try {
            $openAiResponse = $this->callOpenAI($prompt);

            if ($openAiResponse->successful()) {
                $data = $openAiResponse->json();
                $text = $data['choices'][0]['message']['content'] ?? null;

                if ($text) return $this->saveAndRedirect($case, $text, 'OpenAI');
            }
            Log::warning('OpenAI Failed: ' . $openAiResponse->body());
        } catch (Exception $e) {
            Log::warning('OpenAI Connection Error: ' . $e->getMessage());
        }

        // --- STEP 3: TRY OLLAMA (Local Offline Backup) ---
        try {
            $ollamaResponse = $this->callOllama($prompt);

            if ($ollamaResponse->successful()) {
                $data = $ollamaResponse->json();
                $text = $data['message']['content'] ?? null;

                if ($text) return $this->saveAndRedirect($case, $text, 'Ollama (Local)');
            }
            Log::error('Ollama Failed: ' . $ollamaResponse->body());
        } catch (Exception $e) {
            Log::error('Ollama Connection Error: ' . $e->getMessage());
        }

        return back()->with('error', 'All AI providers failed. Please check your internet connection or start Ollama.');
    }

    // --- HELPER FUNCTIONS ---

    /**
     * Unified Gemini Call (Accepts config key dynamically)
     */
    private function callGemini($prompt, $configKey)
    {
        $apiKey = config($configKey);

        // If key is missing in .env, return null immediately (don't waste an HTTP call)
        if (!$apiKey) return null;

        return Http::withOptions(['verify' => false, 'timeout' => 20])
            ->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]
            ]);
    }

    private function callOpenAI($prompt)
    {
        return Http::withOptions(['verify' => false, 'timeout' => 20])
            ->withToken(config('services.openai.key'))
            ->post("https://api.openai.com/v1/chat/completions", [
                'model' => 'gpt-4o-mini',
                'messages' => [['role' => 'user', 'content' => $prompt]],
                'temperature' => 0.3
            ]);
    }

    private function callOllama($prompt)
    {
        // Use 127.0.0.1 to avoid IPv6 issues
        $url = "http://127.0.0.1:11434/api/chat";
        Log::info("Connecting to Ollama at: $url");

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

    private function saveAndRedirect($case, $text, $provider)
    {
        $case->update(['ai_analysis' => $text]);
        return back()->with('success', "Strategy generated successfully via {$provider}!");
    }

    private function prepareContext(LegalCase $case)
    {
        $data = "CASE TITLE: " . ($case->title ?? 'Untitled') . "\n";
        $data .= "DESCRIPTION: " . ($case->description ?? 'No description provided.') . "\n\n";

        if ($case->witnesses && $case->witnesses->count() > 0) {
            $data .= "WITNESS TESTIMONIES:\n";
            foreach ($case->witnesses as $index => $witness) {
                $data .= ($index + 1) . ". Name: {$witness->name} | Type: {$witness->type}\n";
                $data .= "   Statement: \"{$witness->statement}\"\n";
            }
        } else {
            $data .= "WITNESSES: None provided yet.\n";
        }

        // Add Evidence summary if available
        if ($case->evidence && $case->evidence->count() > 0) {
            $data .= "\nEVIDENCE LOG:\n";
            foreach ($case->evidence as $ev) {
                $data .= "- {$ev->title} ({$ev->type})\n";
            }
        }

        return $data;
    }

    private function preparePrompt($context)
    {
        return "You are a senior legal partner. Analyze the following case data and provide a comprehensive strategy memo in Markdown format. Focus on Kenyan Law where applicable.\n\nCASE DATA:\n{$context}";
    }
}
