<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Services\AI\Phi3Service;
use App\Services\AI\GeminiService;
use App\Models\CallLog;
use App\Models\Conversation;
use App\Models\ConversationMessage;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;

class ClientTestController extends Controller
{
    protected $aiService;
    protected $geminiService;

    public function __construct()
    {
        $this->aiService = new Phi3Service();
        $this->geminiService = new GeminiService();
    }

    /**
     * Test AI Connection - Simple health check
     */
    public function testConnection(): JsonResponse
    {
        try {
            $result = $this->aiService->testConnection();
            
            return response()->json([
                'success' => $result['success'],
                'message' => 'AI System Status Check',
                'timestamp' => now()->toISOString(),
                'details' => $result['details'] ?? null,
                'system_status' => 'operational'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'AI System Unavailable',
                'error' => $e->getMessage(),
                'timestamp' => now()->toISOString()
            ], 500);
        }
    }

    /**
     * Simulate Phone Call Conversation
     * This simulates what happens when someone calls your Twilio number
     */
    public function simulatePhoneCall(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'caller_phone' => 'required|string',
            'message' => 'required|string|max:500',
            'conversation_type' => 'string|in:general,sales,support,technical'
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => 'Validation failed',
                'errors' => $validator->errors()
            ], 400);
        }

        try {
            $callerPhone = $request->input('caller_phone');
            $message = $request->input('message');
            $conversationType = $request->input('conversation_type', 'general');

            // Log the simulated call
            $this->logSimulatedCall($callerPhone, $message);

            // Process with AI (same as real phone call)
            $aiResponse = $this->processWithAI($message, $callerPhone, $conversationType);

            return response()->json([
                'success' => true,
                'message' => 'Phone call simulation completed',
                'data' => [
                    'caller_phone' => $callerPhone,
                    'user_message' => $message,
                    'ai_response' => $aiResponse['response'],
                    'response_time_ms' => $aiResponse['response_time_ms'] ?? 0,
                    'model_used' => $aiResponse['model'] ?? 'unknown',
                    'conversation_type' => $conversationType,
                    'timestamp' => now()->toISOString()
                ]
            ]);

        } catch (\Exception $e) {
            Log::error('Phone call simulation failed: ' . $e->getMessage());
            
            return response()->json([
                'success' => false,
                'message' => 'Phone call simulation failed',
                'error' => $e->getMessage(),
                'timestamp' => now()->toISOString()
            ], 500);
        }
    }

    /**
     * Test AI Response Quality
     * Test different types of messages to see AI responses
     */
    public function testAIResponses(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'test_messages' => 'required|array|min:1|max:10',
            'test_messages.*' => 'required|string|max:500',
            'conversation_type' => 'string|in:general,sales,support,technical'
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => 'Validation failed',
                'errors' => $validator->errors()
            ], 400);
        }

        try {
            $testMessages = $request->input('test_messages');
            $conversationType = $request->input('conversation_type', 'general');
            $results = [];

            foreach ($testMessages as $index => $message) {
                $startTime = microtime(true);
                
                $aiResponse = $this->processWithAI($message, 'test_' . $index, $conversationType);
                
                $responseTime = round((microtime(true) - $startTime) * 1000, 2);

                $results[] = [
                    'test_number' => $index + 1,
                    'user_message' => $message,
                    'ai_response' => $aiResponse['response'],
                    'response_time_ms' => $responseTime,
                    'model_used' => $aiResponse['model'] ?? 'unknown',
                    'success' => $aiResponse['success'] ?? false
                ];
            }

            return response()->json([
                'success' => true,
                'message' => 'AI response testing completed',
                'data' => [
                    'total_tests' => count($testMessages),
                    'conversation_type' => $conversationType,
                    'results' => $results,
                    'timestamp' => now()->toISOString()
                ]
            ]);

        } catch (\Exception $e) {
            Log::error('AI response testing failed: ' . $e->getMessage());
            
            return response()->json([
                'success' => false,
                'message' => 'AI response testing failed',
                'error' => $e->getMessage(),
                'timestamp' => now()->toISOString()
            ], 500);
        }
    }

    /**
     * Test Webhook Simulation
     * Simulate what happens when Twilio sends webhook data
     */
    public function simulateWebhook(Request $request): JsonResponse
    {
        try {
            // Simulate Twilio webhook data
            $webhookData = [
                'CallSid' => 'CA' . uniqid(),
                'From' => $request->input('from_phone', '+1234567890'),
                'To' => config('twilio.phone_number'),
                'CallStatus' => 'in-progress',
                'Direction' => 'inbound',
                'SpeechResult' => $request->input('speech_result', 'Hello, I need help with your services'),
                'Confidence' => '0.95',
                'timestamp' => now()->toISOString()
            ];

            // Process the webhook data (same as real Twilio webhook)
            $response = $this->processWebhookData($webhookData);

            return response()->json([
                'success' => true,
                'message' => 'Webhook simulation completed',
                'data' => [
                    'webhook_received' => $webhookData,
                    'ai_response' => $response['ai_response'],
                    'twiml_response' => $response['twiml_response'],
                    'call_logged' => $response['call_logged'],
                    'timestamp' => now()->toISOString()
                ]
            ]);

        } catch (\Exception $e) {
            Log::error('Webhook simulation failed: ' . $e->getMessage());
            
            return response()->json([
                'success' => false,
                'message' => 'Webhook simulation failed',
                'error' => $e->getMessage(),
                'timestamp' => now()->toISOString()
            ], 500);
        }
    }

    /**
     * Get System Performance Metrics
     */
    public function getPerformanceMetrics(): JsonResponse
    {
        try {
            // Test AI response time
            $startTime = microtime(true);
            $testResponse = $this->aiService->generateResponse('Hello', [], 'general');
            $responseTime = round((microtime(true) - $startTime) * 1000, 2);

            // Get recent call statistics
            $recentCalls = CallLog::where('created_at', '>=', now()->subDays(7))->count();
            $successfulCalls = CallLog::where('status', 'completed')
                ->where('created_at', '>=', now()->subDays(7))
                ->count();

            return response()->json([
                'success' => true,
                'message' => 'Performance metrics retrieved',
                'data' => [
                    'ai_response_time_ms' => $responseTime,
                    'ai_available' => $testResponse['success'] ?? false,
                    'recent_calls_7_days' => $recentCalls,
                    'successful_calls_7_days' => $successfulCalls,
                    'success_rate' => $recentCalls > 0 ? round(($successfulCalls / $recentCalls) * 100, 2) : 0,
                    'system_uptime' => 'operational',
                    'timestamp' => now()->toISOString()
                ]
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to get performance metrics',
                'error' => $e->getMessage(),
                'timestamp' => now()->toISOString()
            ], 500);
        }
    }

    /**
     * Test Different Conversation Scenarios
     */
    public function testScenarios(): JsonResponse
    {
        try {
            $scenarios = [
                'greeting' => 'Hello, I\'m interested in your services',
                'pricing' => 'What are your prices for software development?',
                'support' => 'I need help with my existing project',
                'technical' => 'Do you work with React and Laravel?',
                'scheduling' => 'Can I schedule a meeting with your team?',
                'complaint' => 'I\'m not satisfied with the service',
                'compliment' => 'Your team did an excellent job on our project'
            ];

            $results = [];

            foreach ($scenarios as $scenario => $message) {
                $startTime = microtime(true);
                $aiResponse = $this->processWithAI($message, 'scenario_test', 'general');
                $responseTime = round((microtime(true) - $startTime) * 1000, 2);

                $results[] = [
                    'scenario' => $scenario,
                    'message' => $message,
                    'ai_response' => $aiResponse['response'],
                    'response_time_ms' => $responseTime,
                    'success' => $aiResponse['success'] ?? false
                ];
            }

            return response()->json([
                'success' => true,
                'message' => 'Scenario testing completed',
                'data' => [
                    'total_scenarios' => count($scenarios),
                    'results' => $results,
                    'timestamp' => now()->toISOString()
                ]
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Scenario testing failed',
                'error' => $e->getMessage(),
                'timestamp' => now()->toISOString()
            ], 500);
        }
    }

    /**
     * Process message with AI (same logic as phone system)
     */
    private function processWithAI($message, $phoneNumber, $conversationType = 'general')
    {
        try {
            $startTime = microtime(true);
            
            // Use the same AI service as the phone system
            $response = $this->aiService->generateResponse($message, [], $conversationType);
            
            $responseTime = round((microtime(true) - $startTime) * 1000, 2);

            return [
                'success' => $response['success'] ?? false,
                'response' => $response['response'] ?? 'I apologize, but I\'m having trouble processing your request right now.',
                'model' => $response['model'] ?? 'unknown',
                'response_time_ms' => $responseTime
            ];

        } catch (\Exception $e) {
            Log::error('AI processing failed: ' . $e->getMessage());
            
            return [
                'success' => false,
                'response' => 'Thank you for calling. I\'m experiencing technical difficulties. Please try again later.',
                'model' => 'fallback',
                'response_time_ms' => 0
            ];
        }
    }

    /**
     * Process webhook data (simulate Twilio webhook processing)
     */
    private function processWebhookData($webhookData)
    {
        try {
            // Log the call
            $this->logSimulatedCall($webhookData['From'], $webhookData['SpeechResult']);

            // Process with AI
            $aiResponse = $this->processWithAI($webhookData['SpeechResult'], $webhookData['From']);

            // Generate TwiML response (simplified)
            $twimlResponse = '<?xml version="1.0" encoding="UTF-8"?>
<Response>
    <Say voice="Polly.Joanna">' . htmlspecialchars($aiResponse['response']) . '</Say>
    <Gather input="speech" action="' . route('twilio.speech') . '" method="POST" timeout="3" speechTimeout="1">
        <Say voice="Polly.Joanna">Is there anything else I can help you with?</Say>
    </Gather>
    <Say voice="Polly.Joanna">Thank you for calling. Have a great day!</Say>
    <Hangup/>
</Response>';

            return [
                'ai_response' => $aiResponse['response'],
                'twiml_response' => $twimlResponse,
                'call_logged' => true
            ];

        } catch (\Exception $e) {
            Log::error('Webhook processing failed: ' . $e->getMessage());
            
            return [
                'ai_response' => 'Thank you for calling. I\'m experiencing technical difficulties.',
                'twiml_response' => '<?xml version="1.0" encoding="UTF-8"?><Response><Say>Thank you for calling. Please try again later.</Say><Hangup/></Response>',
                'call_logged' => false
            ];
        }
    }

    /**
     * Log simulated call
     */
    private function logSimulatedCall($phoneNumber, $message)
    {
        try {
            CallLog::create([
                'from_number' => $phoneNumber,
                'to_number' => config('twilio.phone_number'),
                'direction' => 'inbound',
                'status' => 'simulated',
                'started_at' => now(),
                'user_id' => null
            ]);
        } catch (\Exception $e) {
            Log::error('Failed to log simulated call: ' . $e->getMessage());
        }
    }
}
