<?php

namespace App\Services\AI;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use App\Services\AI\GeminiService;

class Phi3Service
{
    private $modelUrl;
    private $apiKey;
    private $maxTokens;
    private $temperature;
    private $modelName;

    public function __construct()
    {
        $this->modelUrl = config('ai.phi3.url', 'http://localhost:11434/api/generate');
        $this->apiKey = config('ai.phi3.api_key', 'gemma-2b-key');
        $this->maxTokens = config('ai.phi3.max_tokens', 100);
        $this->temperature = config('ai.phi3.temperature', 0.3);
    }

    /**
     * Set the model dynamically
     */
    public function setModel(string $model): void
    {
        $this->modelName = $model;
    }

    /**
     * Generate AI response for conversation
     */
    public function generateResponse(string $message, array $context = [], string $conversationType = 'general'): array
    {
        try {
            // Try Gemini first (much faster)
            $geminiService = new GeminiService();
            $geminiResponse = $geminiService->generateResponse($message, $context, $conversationType);
            
            if ($geminiResponse['success']) {
                return $geminiResponse;
            }
            
            // Fallback to local Ollama if Gemini fails
            Log::warning('Gemini failed, falling back to Ollama: ' . $geminiResponse['error']);
            
            // Ultra-fast, minimal prompt for speed
            $prompt = "User: " . $message . "\nAssistant:";

            $payload = [
                'model' => 'gemma:2b',
                'prompt' => $prompt,
                'stream' => false,
                'options' => [
                    'temperature' => $this->temperature,
                    'num_predict' => $this->maxTokens,
                    'top_k' => 10,
                    'top_p' => 0.9,
                    'repeat_penalty' => 1.1
                ]
            ];

            $response = Http::timeout(5)
                ->withHeaders([
                    'Content-Type' => 'application/json'
                ])
                ->post($this->modelUrl, $payload);

            if ($response->successful()) {
                $data = $response->json();
                $responseText = trim($data['response'] ?? '');
                
                // Make response very concise for speed
                if (strlen($responseText) > 150) {
                    $responseText = substr($responseText, 0, 150) . '...';
                }
                
                return [
                    'success' => true,
                    'response' => $responseText,
                    'usage' => [
                        'prompt_tokens' => $data['prompt_eval_count'] ?? 0,
                        'completion_tokens' => $data['eval_count'] ?? 0,
                        'total_tokens' => ($data['prompt_eval_count'] ?? 0) + ($data['eval_count'] ?? 0)
                    ],
                    'model' => $data['model'] ?? 'gemma:2b'
                ];
            }

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

        } catch (\Exception $e) {
            Log::error('Phi3Service 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 = [
            'contact_name' => $contactData['name'] ?? 'Unknown',
            'company' => $contactData['company'] ?? 'Unknown Company',
            'call_type' => $callType,
            'previous_interactions' => $contactData['interactions'] ?? []
        ];

        return $this->generateResponse($message, $context, 'crm');
    }

    /**
     * Analyze conversation sentiment
     */
    public function analyzeSentiment(string $message): array
    {
        $prompt = "Analyze the sentiment of this message and return only a JSON response with 'sentiment' (positive/negative/neutral) and 'confidence' (0-1): " . $message;
        
        $response = $this->generateResponse($prompt, [], 'sentiment');
        
        if ($response['success']) {
            $content = $response['response'];
            $json = json_decode($content, true);
            
            if ($json) {
                return [
                    'success' => true,
                    'sentiment' => $json['sentiment'] ?? 'neutral',
                    'confidence' => $json['confidence'] ?? 0.5
                ];
            }
        }

        return [
            'success' => false,
            'sentiment' => 'neutral',
            'confidence' => 0.5
        ];
    }

    /**
     * Extract key information from conversation
     */
    public function extractInsights(string $message, array $context = []): array
    {
        $prompt = "Extract key information from this conversation message. Return JSON with: intent, entities, action_items, next_steps. Message: " . $message;
        
        $response = $this->generateResponse($prompt, $context, 'extraction');
        
        if ($response['success']) {
            $content = $response['response'];
            $json = json_decode($content, true);
            
            if ($json) {
                return [
                    'success' => true,
                    'insights' => $json
                ];
            }
        }

        return [
            'success' => false,
            'insights' => []
        ];
    }

    /**
     * Get system prompt based on conversation type
     */
    private function getSystemPrompt(string $type): string
    {
        $prompts = [
            'general' => "You are DizzCall AI, an intelligent voice agent for CRM and business automation. Provide helpful, concise responses.",
            'crm' => "You are a CRM specialist. Help with contact management, lead tracking, and customer relationship tasks.",
            'sales' => "You are a sales expert. Provide guidance on sales strategies, lead qualification, and closing techniques.",
            'support' => "You are a customer support specialist. Help resolve customer issues and provide technical assistance.",
            'sentiment' => "Analyze the emotional tone and sentiment of the conversation. Provide insights on customer mood and satisfaction.",
            'extraction' => "Extract key information from conversations including contact details, requirements, and action items."
        ];

        return $prompts[$type] ?? $prompts['general'];
    }

    /**
     * Format conversation history for API
     */
    private function formatConversationHistory(array $context): array
    {
        $history = [];
        
        if (isset($context['previous_messages'])) {
            foreach ($context['previous_messages'] as $message) {
                $history[] = [
                    'role' => $message['role'] ?? 'user',
                    'content' => $message['content'] ?? ''
                ];
            }
        }

        return $history;
    }


    /**
     * Test AI service connection
     */
    public function testConnection(): array
    {
        try {
            // Test Gemini first
            $geminiService = new GeminiService();
            $geminiTest = $geminiService->testConnection();
            
            if ($geminiTest['success']) {
                return [
                    'success' => true,
                    'message' => 'Gemini API connection successful (Primary)',
                    'model' => 'gemini-1.5-flash',
                    'response_time_ms' => 0
                ];
            }
            
            // Fallback to local test
            $response = $this->generateResponse("Hello, this is a test message.");
            
            return [
                'success' => $response['success'],
                'message' => $response['success'] ? 'Local AI service working (Fallback)' : 'Both Gemini and local AI services failed',
                'details' => $response
            ];
            
        } catch (\Exception $e) {
            return [
                'success' => false,
                'message' => 'AI service connection failed: ' . $e->getMessage()
            ];
        }
    }

}
