<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Services\AI\CRMIntelligenceService;
use App\Services\AI\TrainingDataService;
use App\Models\User;
use App\Models\Conversation;

class TestCRMIntelligenceCommand extends Command
{
    protected $signature = 'ai:test-crm';
    protected $description = 'Test CRM intelligence features';

    public function handle()
    {
        $this->info('🧠 Testing CRM Intelligence Features...');
        $this->line('=====================================');

        try {
            // Get or create a test user
            $user = User::first();
            if (!$user) {
                $this->error('No users found. Please create a user first.');
                return;
            }

            $this->line("Testing with user: {$user->name} (ID: {$user->id})");

            // Test CRM Intelligence Service
            $crmService = new CRMIntelligenceService(app(\App\Services\AI\Phi3Service::class));
            
            $this->line('');
            $this->info('📊 Testing Customer Behavior Analysis...');
            $behaviorResult = $crmService->analyzeCustomerBehavior($user->id);
            
            if ($behaviorResult['success']) {
                $this->info('✅ Customer Behavior Analysis Successful!');
                $this->line('Profile: ' . json_encode($behaviorResult['customer_profile'], JSON_PRETTY_PRINT));
            } else {
                $this->error('❌ Customer Behavior Analysis Failed: ' . $behaviorResult['error']);
            }

            $this->line('');
            $this->info('🎯 Testing Lead Scoring...');
            $leadScoreResult = $crmService->generateLeadScore($user->id);
            
            if ($leadScoreResult['success']) {
                $this->info('✅ Lead Scoring Successful!');
                $this->line('Lead Score: ' . $leadScoreResult['lead_score']);
                $this->line('Lead Status: ' . $leadScoreResult['lead_status']);
            } else {
                $this->error('❌ Lead Scoring Failed: ' . $leadScoreResult['error']);
            }

            $this->line('');
            $this->info('💡 Testing Conversation Suggestions...');
            $suggestionsResult = $crmService->generateConversationSuggestions($user->id, 'sales', ['context' => 'test']);
            
            if ($suggestionsResult['success']) {
                $this->info('✅ Conversation Suggestions Generated!');
                $this->line('Suggestions: ' . json_encode($suggestionsResult['suggestions'], JSON_PRETTY_PRINT));
            } else {
                $this->error('❌ Conversation Suggestions Failed: ' . $suggestionsResult['error']);
            }

            $this->line('');
            $this->info('📈 Testing Sentiment Trends...');
            $sentimentResult = $crmService->analyzeSentimentTrends($user->id, 30);
            
            if ($sentimentResult['success']) {
                $this->info('✅ Sentiment Analysis Successful!');
                $this->line('Overall Trend: ' . $sentimentResult['overall_trend']);
            } else {
                $this->error('❌ Sentiment Analysis Failed: ' . $sentimentResult['error']);
            }

            $this->line('');
            $this->info('🔄 Testing Follow-up Recommendations...');
            $followUpResult = $crmService->generateFollowUpRecommendations($user->id);
            
            if ($followUpResult['success']) {
                $this->info('✅ Follow-up Recommendations Generated!');
                $this->line('Total Recommendations: ' . $followUpResult['total_recommendations']);
            } else {
                $this->error('❌ Follow-up Recommendations Failed: ' . $followUpResult['error']);
            }

            // Test Training Data Service
            $this->line('');
            $this->info('📚 Testing Training Data Collection...');
            $trainingService = new TrainingDataService(app(\App\Services\AI\Phi3Service::class));
            
            $trainingResult = $trainingService->collectTrainingData($user->id, 30);
            
            if ($trainingResult['success']) {
                $this->info('✅ Training Data Collection Successful!');
                $this->line('Conversations Processed: ' . $trainingResult['conversations_processed']);
                $this->line('File Path: ' . $trainingResult['file_path']);
            } else {
                $this->error('❌ Training Data Collection Failed: ' . $trainingResult['error']);
            }

            $this->line('');
            $this->info('🎉 All CRM Intelligence tests completed!');

        } catch (\Exception $e) {
            $this->error('❌ Error: ' . $e->getMessage());
            $this->line('Stack trace: ' . $e->getTraceAsString());
        }
    }
}
