<?php

namespace App\Services\AI;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class GeminiService
{
    private $apiKey;
    private $apiUrl;
    private $maxTokens;
    private $temperature;

    public function __construct()
    {
        $this->apiKey = config('ai.gemini.api_key');
        $this->apiUrl = config('ai.gemini.api_url', 'https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent');
        $this->maxTokens = config('ai.gemini.max_tokens', 100);
        $this->temperature = config('ai.gemini.temperature', 0.3);
    }

    /**
     * Generate AI response using Gemini with streaming support
     */
    public function generateResponse(string $message, array $context = [], string $conversationType = 'general'): array
    {
        try {
            // Build context for CRM calls
            $contextString = '';
            if (!empty($context)) {
                $contextString = "\nContext: " . implode(', ', $context);
            }

            // Dizaart Systems AI Assistant - Optimized Prompt
            $systemPrompt = "You are Alex from Dizaart Systems. You're a friendly, professional customer support rep. 

Dizaart offers: Custom software, mobile apps, Salesforce solutions, video editing, digital marketing, AI automation, IT support, and smart integrations.

Be conversational, helpful, and concise. For meetings, ask: name, purpose, company. Contact: info@dizaartsystems.com

User: {$message}
Alex:";

            $prompt = $systemPrompt;

            $payload = [
                'contents' => [
                    [
                        'parts' => [
                            ['text' => $prompt]
                        ]
                    ]
                ],
                'generationConfig' => [
                    'maxOutputTokens' => $this->maxTokens,
                    'temperature' => $this->temperature,
                    'topK' => 5,
                    'topP' => 0.8,
                    'stopSequences' => []
                ],
                'safetySettings' => [
                    [
                        'category' => 'HARM_CATEGORY_HARASSMENT',
                        'threshold' => 'BLOCK_MEDIUM_AND_ABOVE'
                    ],
                    [
                        'category' => 'HARM_CATEGORY_HATE_SPEECH',
                        'threshold' => 'BLOCK_MEDIUM_AND_ABOVE'
                    ],
                    [
                        'category' => 'HARM_CATEGORY_SEXUALLY_EXPLICIT',
                        'threshold' => 'BLOCK_MEDIUM_AND_ABOVE'
                    ],
                    [
                        'category' => 'HARM_CATEGORY_DANGEROUS_CONTENT',
                        'threshold' => 'BLOCK_MEDIUM_AND_ABOVE'
                    ]
                ]
            ];

            $response = Http::timeout(5)
                ->withHeaders([
                    'Content-Type' => 'application/json',
                    'x-goog-api-key' => $this->apiKey
                ])
                ->post($this->apiUrl, $payload);

            if ($response->successful()) {
                $data = $response->json();
                
                if (isset($data['candidates'][0]['content']['parts'][0]['text'])) {
                    $responseText = trim($data['candidates'][0]['content']['parts'][0]['text']);
                    
                    return [
                        'success' => true,
                        'response' => $responseText,
                        'usage' => [
                            'prompt_tokens' => $data['usageMetadata']['promptTokenCount'] ?? 0,
                            'completion_tokens' => $data['usageMetadata']['candidatesTokenCount'] ?? 0,
                            'total_tokens' => $data['usageMetadata']['totalTokenCount'] ?? 0
                        ],
                        'model' => 'gemini-1.5-flash'
                    ];
                }
            }

            return [
                'success' => false,
                'error' => 'API request failed: ' . $response->body()
            ];

        } catch (\Exception $e) {
            Log::error('GeminiService Error: ' . $e->getMessage());
            return [
                'success' => false,
                'error' => 'Service unavailable: ' . $e->getMessage()
            ];
        }
    }

    /**
     * Generate CRM-specific responses
     */
    public function generateCRMResponse(string $message, array $contactData = [], string $callType = 'sales'): array
    {
        $context = [];
        
        if (!empty($contactData)) {
            $context[] = "Contact: " . ($contactData['name'] ?? 'Unknown');
            $context[] = "Phone: " . ($contactData['phone'] ?? 'Unknown');
            $context[] = "Company: " . ($contactData['company'] ?? 'Unknown');
        }
        
        $context[] = "Call Type: " . $callType;
        
        return $this->generateResponse($message, $context, 'crm');
    }

    /**
     * Test connection to Gemini API
     */
    public function testConnection(): array
    {
        try {
            $testResponse = $this->generateResponse("Hello, test connection");
            
            if ($testResponse['success']) {
                return [
                    'success' => true,
                    'message' => 'Gemini API connection successful',
                    'model' => 'gemini-1.5-flash',
                    'response_time_ms' => 0 // Gemini is very fast
                ];
            }
            
            return [
                'success' => false,
                'message' => 'Gemini API test failed: ' . $testResponse['error']
            ];
            
        } catch (\Exception $e) {
            return [
                'success' => false,
                'message' => 'Gemini API connection failed: ' . $e->getMessage()
            ];
        }
    }
}
