<?php

namespace App\Services\AI;

use App\Models\Conversation;
use App\Models\ConversationMessage;
use App\Models\AIInsight;
use App\Models\Contact;
use App\Services\AI\Phi3Service;
use Illuminate\Support\Facades\Log;

class ConversationService
{
    private $phi3Service;

    public function __construct(Phi3Service $phi3Service)
    {
        $this->phi3Service = $phi3Service;
    }

    /**
     * Start a new conversation
     */
    public function startConversation(int $userId, int $contactId = null, string $type = 'general', array $context = []): Conversation
    {
        $conversation = Conversation::create([
            'user_id' => $userId,
            'contact_id' => $contactId,
            'session_id' => $this->generateSessionId(),
            'type' => $type,
            'status' => 'active',
            'context_data' => $context,
            'ai_model' => 'phi3-mini',
            'started_at' => now()
        ]);

        // Add welcome message
        $this->addWelcomeMessage($conversation);

        return $conversation;
    }

    /**
     * Process user message and generate AI response
     */
    public function processMessage(int $conversationId, string $message, array $metadata = []): array
    {
        $conversation = Conversation::findOrFail($conversationId);
        
        // Add user message
        $userMessage = $conversation->addMessage('user', $message, $metadata);

        // Get conversation context
        $context = $this->buildContext($conversation);

        // Generate AI response
        $aiResponse = $this->phi3Service->generateCRMResponse(
            $message, 
            $context['contact_data'] ?? [], 
            $conversation->type
        );

        if ($aiResponse['success']) {
            // Add AI response message
            $aiMessage = $conversation->addMessage('assistant', $aiResponse['response'], [
                'model' => $aiResponse['model'] ?? 'phi3-mini',
                'usage' => $aiResponse['usage'] ?? [],
                'processing_time' => microtime(true) - ($metadata['start_time'] ?? microtime(true))
            ]);

            // Analyze message for insights
            $this->analyzeMessage($conversation, $userMessage, $aiMessage);

            // Update conversation statistics
            $this->updateConversationStats($conversation);

            return [
                'success' => true,
                'conversation_id' => $conversation->id,
                'user_message' => $userMessage,
                'ai_message' => $aiMessage,
                'insights' => $this->getRecentInsights($conversation)
            ];
        }

        return [
            'success' => false,
            'error' => $aiResponse['error'] ?? 'Failed to generate response'
        ];
    }

    /**
     * Analyze message for AI insights
     */
    private function analyzeMessage(Conversation $conversation, ConversationMessage $userMessage, ConversationMessage $aiMessage): void
    {
        try {
            // Analyze sentiment
            $sentiment = $this->phi3Service->analyzeSentiment($userMessage->content);
            if ($sentiment['success']) {
                $userMessage->update([
                    'sentiment' => $sentiment['sentiment'],
                    'confidence_score' => $sentiment['confidence']
                ]);
            }

            // Extract insights
            $insights = $this->phi3Service->extractInsights($userMessage->content, $conversation->context_data);
            if ($insights['success']) {
                $this->saveInsights($conversation, $userMessage, $insights['insights']);
            }

        } catch (\Exception $e) {
            Log::error('Conversation analysis error: ' . $e->getMessage());
        }
    }

    /**
     * Save AI insights to database
     */
    private function saveInsights(Conversation $conversation, ConversationMessage $message, array $insights): void
    {
        $insightTypes = [
            'intent' => 'intent',
            'entities' => 'entity',
            'action_items' => 'action_item',
            'next_steps' => 'next_step'
        ];

        foreach ($insightTypes as $key => $type) {
            if (isset($insights[$key]) && !empty($insights[$key])) {
                AIInsight::create([
                    'conversation_id' => $conversation->id,
                    'message_id' => $message->id,
                    'insight_type' => $type,
                    'content' => is_array($insights[$key]) ? json_encode($insights[$key]) : $insights[$key],
                    'confidence_score' => 0.8, // Default confidence
                    'metadata' => ['source' => 'phi3-mini'],
                    'processed_at' => now()
                ]);
            }
        }
    }

    /**
     * Build conversation context
     */
    private function buildContext(Conversation $conversation): array
    {
        $context = [
            'conversation_id' => $conversation->id,
            'type' => $conversation->type,
            'previous_messages' => $conversation->messages()
                ->orderBy('timestamp', 'desc')
                ->limit(10)
                ->get()
                ->map(function ($message) {
                    return [
                        'role' => $message->role,
                        'content' => $message->content,
                        'timestamp' => $message->timestamp
                    ];
                })
                ->toArray()
        ];

        // Add contact data if available
        if ($conversation->contact_id) {
            $contact = Contact::find($conversation->contact_id);
            if ($contact) {
                $context['contact_data'] = [
                    'name' => $contact->name,
                    'company' => $contact->company_name,
                    'email' => $contact->email,
                    'phone' => $contact->contact_number,
                    'interactions' => $contact->interactions ?? []
                ];
            }
        }

        return $context;
    }

    /**
     * Update conversation statistics
     */
    private function updateConversationStats(Conversation $conversation): void
    {
        $messages = $conversation->messages;
        $userMessages = $messages->where('role', 'user');
        
        // Calculate average sentiment
        $sentimentScores = $userMessages->whereNotNull('sentiment')
            ->pluck('confidence_score')
            ->filter()
            ->values();

        $avgSentiment = $sentimentScores->isNotEmpty() ? $sentimentScores->avg() : null;

        $conversation->update([
            'total_messages' => $messages->count(),
            'sentiment_score' => $avgSentiment,
            'duration_seconds' => $conversation->started_at ? now()->diffInSeconds($conversation->started_at) : 0
        ]);
    }

    /**
     * Get recent insights for conversation
     */
    private function getRecentInsights(Conversation $conversation): array
    {
        return $conversation->insights()
            ->orderBy('processed_at', 'desc')
            ->limit(5)
            ->get()
            ->map(function ($insight) {
                return [
                    'type' => $insight->insight_type,
                    'content' => $insight->content,
                    'confidence' => $insight->confidence_score,
                    'icon' => $insight->icon
                ];
            })
            ->toArray();
    }

    /**
     * Add welcome message to conversation
     */
    private function addWelcomeMessage(Conversation $conversation): void
    {
        $welcomeMessages = [
            'sales' => "Hello! I'm your AI sales assistant. How can I help you today?",
            'support' => "Hi there! I'm here to help you with any questions or issues you might have.",
            'follow_up' => "Hello! I'm following up on our previous conversation. How are things going?",
            'general' => "Hello! I'm your AI assistant. How can I help you today?"
        ];

        $message = $welcomeMessages[$conversation->type] ?? $welcomeMessages['general'];
        
        $conversation->addMessage('assistant', $message, [
            'type' => 'welcome',
            'ai_generated' => true
        ]);
    }

    /**
     * Generate session ID
     */
    private function generateSessionId(): string
    {
        return 'conv_' . time() . '_' . substr(md5(uniqid()), 0, 8);
    }

    /**
     * Complete conversation
     */
    public function completeConversation(int $conversationId, string $outcome = null, string $summary = null): Conversation
    {
        $conversation = Conversation::findOrFail($conversationId);
        $conversation->complete($outcome, $summary);
        
        return $conversation;
    }

    /**
     * Get conversation analytics
     */
    public function getConversationAnalytics(int $conversationId): array
    {
        $conversation = Conversation::with(['messages', 'insights'])->findOrFail($conversationId);
        
        return [
            'conversation' => $conversation,
            'statistics' => $conversation->getStatistics(),
            'insights' => $conversation->insights->groupBy('insight_type'),
            'messages' => $conversation->messages->take(20) // Last 20 messages
        ];
    }
}
