<?php

namespace App\Http\Controllers\AI;

use App\Http\Controllers\Controller;
use App\Services\AI\ConversationService;
use App\Services\AI\Phi3Service;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Validator;

class AIAPIController extends Controller
{
    private $conversationService;
    private $phi3Service;

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

    /**
     * Test AI service connection
     */
    public function testConnection(): JsonResponse
    {
        try {
            $result = $this->phi3Service->testConnection();

            return response()->json([
                'success' => $result['success'],
                'message' => $result['message'],
                'details' => $result['details'] ?? null
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'AI service test failed',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Start a new AI conversation (API version - no auth required)
     */
    public function startConversation(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'type' => 'nullable|in:sales,support,follow_up,qualification,demo,general',
            'context' => 'nullable|array',
            'message' => 'nullable|string|max:2000'
        ]);

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

        try {
            // Use a default user ID for API testing (create if doesn't exist)
            $user = User::first();
            if (!$user) {
                // Create a default user for API testing
                $user = User::create([
                    'name' => 'API Test User',
                    'email' => 'api@test.com',
                    'password' => bcrypt('password'),
                    'status' => 'active'
                ]);
            }
            $userId = $user->id;
            
            $conversation = $this->conversationService->startConversation(
                $userId,
                null, // no contact
                $request->type ?? 'general',
                $request->context ?? []
            );

            $response = [
                'success' => true,
                'message' => 'Conversation started successfully',
                'conversation' => $conversation,
                'session_id' => $conversation->session_id
            ];

            // If there's an initial message, process it
            if ($request->message) {
                $messageResult = $this->conversationService->processMessage(
                    $conversation->id,
                    $request->message,
                    ['source' => 'api']
                );

                if ($messageResult['success']) {
                    $response['data'] = $messageResult;
                }
            }

            return response()->json($response);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to start conversation',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Send message to AI and get response (API version)
     */
    public function sendMessage(Request $request, int $conversationId): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'message' => 'required|string|max:2000',
            'metadata' => 'nullable|array'
        ]);

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

        try {
            $result = $this->conversationService->processMessage(
                $conversationId,
                $request->message,
                $request->metadata ?? []
            );

            if ($result['success']) {
                return response()->json([
                    'success' => true,
                    'message' => 'Message processed successfully',
                    'data' => $result
                ]);
            }

            return response()->json([
                'success' => false,
                'message' => 'Failed to process message',
                'error' => $result['error'] ?? 'Unknown error'
            ], 500);

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

    /**
     * Get conversation history (API version)
     */
    public function getConversation(int $conversationId): JsonResponse
    {
        try {
            $analytics = $this->conversationService->getConversationAnalytics($conversationId);

            return response()->json([
                'success' => true,
                'data' => $analytics
            ]);

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

    /**
     * Analyze text sentiment (API version)
     */
    public function analyzeSentiment(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'text' => 'required|string|max:1000'
        ]);

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

        try {
            $result = $this->phi3Service->analyzeSentiment($request->text);

            return response()->json([
                'success' => $result['success'],
                'sentiment' => $result['sentiment'],
                'confidence' => $result['confidence']
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Sentiment analysis failed',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Extract insights from text (API version)
     */
    public function extractInsights(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'text' => 'required|string|max:2000',
            'context' => 'nullable|array'
        ]);

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

        try {
            $result = $this->phi3Service->extractInsights($request->text, $request->context ?? []);

            return response()->json([
                'success' => $result['success'],
                'insights' => $result['insights']
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Insight extraction failed',
                'error' => $e->getMessage()
            ], 500);
        }
    }
}
