<?php

namespace App\Http\Controllers\AI;

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

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

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

    /**
     * Start a new AI conversation
     */
    public function startConversation(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'contact_id' => 'nullable|exists:contacts,id',
            'type' => 'required|in:sales,support,follow_up,qualification,demo,general',
            'context' => 'nullable|array'
        ]);

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

        try {
            $conversation = $this->conversationService->startConversation(
                Auth::id(),
                $request->contact_id,
                $request->type,
                $request->context ?? []
            );

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

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

    /**
     * Send message to AI and get response
     */
    public function sendMessage(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'conversation_id' => 'required|exists:conversations,id',
            '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(
                $request->conversation_id,
                $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
     */
    public function getConversation(Request $request, 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);
        }
    }

    /**
     * Complete conversation
     */
    public function completeConversation(Request $request, int $conversationId): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'outcome' => 'nullable|string|max:255',
            'summary' => 'nullable|string|max:1000'
        ]);

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

        try {
            $conversation = $this->conversationService->completeConversation(
                $conversationId,
                $request->outcome,
                $request->summary
            );

            return response()->json([
                'success' => true,
                'message' => 'Conversation completed successfully',
                'conversation' => $conversation
            ]);

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

    /**
     * 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);
        }
    }

    /**
     * Analyze text sentiment
     */
    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
     */
    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);
        }
    }

    /**
     * Get user's conversations
     */
    public function getUserConversations(Request $request): JsonResponse
    {
        try {
            $conversations = \App\Models\Conversation::where('user_id', Auth::id())
                ->with(['contact', 'messages' => function($query) {
                    $query->latest()->limit(1);
                }])
                ->orderBy('created_at', 'desc')
                ->paginate(20);

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

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