<?php

namespace App\Http\Controllers;

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

class AiChatController extends Controller
{
    /**
     * Send message to AI and get response
     */
    public function sendMessage(Request $request): JsonResponse
    {
        $request->validate([
            'message' => 'required|string|max:1000',
            'conversation_id' => 'nullable|string'
        ]);

        $message = $request->input('message');
        $conversationId = $request->input('conversation_id', uniqid());

        try {
            // Choose AI provider based on configuration
            $response = $this->getAiResponse($message);
            
            return response()->json([
                'success' => true,
                'message' => $response,
                'conversation_id' => $conversationId,
                'timestamp' => now()->toISOString()
            ]);

        } catch (\Exception $e) {
            Log::error('AI Chat Error: ' . $e->getMessage());
            
            return response()->json([
                'success' => false,
                'error' => 'Sorry, I encountered an error. Please try again.',
                'conversation_id' => $conversationId
            ], 500);
        }
    }

    /**
     * Get AI response from configured provider
     */
    private function getAiResponse(string $message): string
    {
        // Primary: DeepSeek API
        if (config('ai.use_deepseek', true)) {
            return $this->getDeepSeekResponse($message);
        }
        
        // Fallback: OpenAI API (commented out by default)
        // if (config('ai.use_openai', false)) {
        //     return $this->getOpenAiResponse($message);
        // }
        
        throw new \Exception('No AI provider configured');
    }

    /**
     * Get response from DeepSeek API
     */
    private function getDeepSeekResponse(string $message): string
    {
        $apiKey = config('ai.deepseek.api_key');
        $model = config('ai.deepseek.model', 'deepseek-chat');
        
        if (!$apiKey) {
            throw new \Exception('DeepSeek API key not configured');
        }

        $response = Http::withHeaders([
            'Authorization' => 'Bearer ' . $apiKey,
            'Content-Type' => 'application/json',
        ])->timeout(30)->post('https://api.deepseek.com/chat/completions', [
            'model' => $model,
            'messages' => [
                [
                    'role' => 'system',
                    'content' => 'You are D-Hero AI, a helpful medical assistant for Doctors Hero platform. Provide helpful, accurate medical information while being professional and empathetic. Always remind users to consult with healthcare professionals for serious medical concerns.'
                ],
                [
                    'role' => 'user',
                    'content' => $message
                ]
            ],
            'max_tokens' => 500,
            'temperature' => 0.7
        ]);

        if (!$response->successful()) {
            throw new \Exception('DeepSeek API request failed: ' . $response->body());
        }

        $data = $response->json();
        
        return $data['choices'][0]['message']['content'] ?? 'I apologize, but I could not generate a response at this time.';
    }

    /**
     * Get response from OpenAI API (Alternative - commented out)
     */
    // private function getOpenAiResponse(string $message): string
    // {
    //     $apiKey = config('ai.openai.api_key');
    //     $model = config('ai.openai.model', 'gpt-3.5-turbo');
    //     
    //     if (!$apiKey) {
    //         throw new \Exception('OpenAI API key not configured');
    //     }

    //     $response = Http::withHeaders([
    //         'Authorization' => 'Bearer ' . $apiKey,
    //         'Content-Type' => 'application/json',
    //     ])->timeout(30)->post('https://api.openai.com/v1/chat/completions', [
    //         'model' => $model,
    //         'messages' => [
    //             [
    //                 'role' => 'system',
    //                 'content' => 'You are D-Hero AI, a helpful medical assistant for Doctors Hero platform. Provide helpful, accurate medical information while being professional and empathetic. Always remind users to consult with healthcare professionals for serious medical concerns.'
    //             ],
    //             [
    //                 'role' => 'user',
    //                 'content' => $message
    //             ]
    //         ],
    //         'max_tokens' => 500,
    //         'temperature' => 0.7
    //     ]);

    //     if (!$response->successful()) {
    //         throw new \Exception('OpenAI API request failed: ' . $response->body());
    //     }

    //     $data = $response->json();
    //     
    //     return $data['choices'][0]['message']['content'] ?? 'I apologize, but I could not generate a response at this time.';
    // }
}