<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Log;
use Illuminate\Http\Request;
use Mcpuishor\QdrantLaravel\Facades\Schema;
use Mcpuishor\QdrantLaravel\Enums\DistanceMetric;
use Mcpuishor\QdrantLaravel\DTOs\Vector;
use Illuminate\Support\Facades\Http;
use OpenAI;

// use OpenAI\Laravel\Facades\OpenAI;

// use OpenAI\Laravel\Facades\OpenAI;

class QdrantController extends Controller
{
    public $collectionName = 'test_collection';
    public function createCollection()
    {
        // define vector parameters
        $vector = [
            'size' => config('qdrant-laravel.vector_size', 1536),
            'distance' => 'Cosine' // or 'Euclid', 'Dot' depending on your use
        ];

        // create collection using positional arguments
        try{
            $response = Schema::create(
                $this->collectionName, // collection name
                $vector            // vector config
            );
            Log::info($response);
        } catch (\Exception $e) {
            return false;
        }

        return true;
    }

    public function checkCollection(string $collectionName)
    {
        $exists = Schema::exists($collectionName);

        if(!$exists) {
           $isCollectionCreated = $this->createCollection();
           return $isCollectionCreated;
        }

    }


    public function deleteCollection(string $collectionName)
    {
        try {
            // Check if collection exists
            if (!Schema::exists($collectionName)) {
                return response()->json([
                    'collection' => $collectionName,
                    'deleted' => false,
                    'message' => 'Collection does not exist'
                ], 404);
            }

            // Delete the collection
            Schema::delete($collectionName);

            return response()->json([
                'collection' => $collectionName,
                'deleted' => true,
                'message' => 'Collection deleted successfully'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'collection' => $collectionName,
                'deleted' => false,
                'message' => 'Error deleting collection: ' . $e->getMessage()
            ], 500);
        }
    }


    public function index(Request $request)
    {
        $collection = $this->collectionName;

        $collectionExits = $this->checkCollection($collection);
        if($collectionExits === false) {
            return response()->json([
                'success' => false,
                'message' => 'Collection does not exist',
            ]);
        }
        $user = $request->user(); // Authenticated user
        $postId   = $request->id;
        $text     = $request->content;
        $title   = $request->title;


            $apiKey = config('openai.api_key');
            $client = OpenAI::client($apiKey);
            $response = $client->embeddings()->create([
                'model' => 'text-embedding-3-small',
                'input' => 'The food was delicious and the waiter...',
            ]);
       
            die('here');

        try{
            $apiKey = config('openai.api_key');
            if (empty($apiKey)) {
                return response()->json([
                    'success' => false,
                    'message' => 'Temporary server error, please try again later.',
                ]);
            }
            Log::info('OpenAI API Key: ' . $apiKey);

            // 1. Create Embedding
            $response = OpenAI::embeddings()->create([
                'model' => 'text-embedding-3-small',
                'input' => "sdjfkd.j"
            ]);
            Log::info('OpenAI Response: ' . json_encode($response));

            // if (!isset($response['data'][0]['embedding'])) {
            //     return response()->json([
            //         'status' => false,
            //         'message' => 'OpenAI returned error',
            //         'response' => $response
            //     ], 500);
            // }
            // Log::info('OpenAI Embedding: ' . json_encode($response['data'][0]['embedding']));

            // $vector = $response['data'][0]['embedding'];
            // Log::info('Qdrant Vector: ' . json_encode($vector));
            // // 2. Prepare Qdrant point data
            // $point = [
            //     'id' => $postId,
            //     'vector' => $vector,
            //     'payload' => [
            //         'id' => $postId,
            //         'title' => $request->title,
            //         'url' => $request->url
            //     ],
            // ];

            // 3. Send to Qdrant
            // $result = app('qdrant')->upsert($collection, [$point]);
            // return response()->json([
            //     'success' => true,
            //     'qdrant' => $result,
            // ]);
        } catch (\Exception $e) {
            Log::error('QDRANT ERROR: ' . $e->getMessage(), [
                'trace' => $e->getTraceAsString()
            ]);
            return response()->json([
                'success' => false,
                'message' => 'Qdrant error',
            ], 500);
        }
    }

    public function viewIndexed()
    {
        $collection = $this->collectionName;
        try {
            
            $qdrant = app('qdrant');

            $collectionExits = $this->checkCollection($collection);
            if($collectionExits === false) {
                return response()->json([
                    'success' => false,
                    'message' => 'Collection does not exist',
                ]);
            }

            // Fetch all points from the collection
            $result = $qdrant->scroll(
                collection: $this->collectionName,
                // limit: 1000 // optional, adjust as needed
            );

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

        } catch (\Exception $e) {
            Log::error('QDRANT ERROR: ' . $e->getMessage(), [
        'trace' => $e->getTraceAsString()
    ]);
            return response()->json([
                'success' => false,
                'error' => $e->getMessage(),
            ], 500);
        }
    }

    public function clearIndexed()
    {
        try {
            if (!Schema::exists($this->collectionName)) {
                return response()->json([
                    'success' => false,
                    'message' => "Collection does not exist.",
                ], 404);
            }
            Schema::delete($this->collectionName);

            return response()->json([
                'success' => true,
                'message' => 'Collection deleted, all indexed data cleared.',
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to clear indexed data: ' . $e->getMessage(),
            ], 500);
        }
    }

}
