<?php

namespace App\Helpers\FirstParty\AI;

use App\Models\KeywordEmbedding;
use Exception;
use Illuminate\Support\Facades\Http;
use Pgvector\Laravel\Vector;

class CloudflareAI
{
    public static function getVectorEmbeddingBgeSmall($embedding_query)
    {
        $embedding_query = substr(trim(preg_replace('/[^a-zA-Z0-9\s,\.]/', '', $embedding_query)), 0, 500);

        if (empty($embedding_query)) {
            throw new Exception('Empty embedding query.');
        }

        $keyword_embedding = KeywordEmbedding::where('keyword', $embedding_query)->first();

        if (! is_null($keyword_embedding)) {
            return $keyword_embedding->embedding;
        }

        $maxRetries = 3;
        $currentAttempt = 0;

        $embedding = null;

        while ($currentAttempt < $maxRetries && $embedding === null) {
            try {
                // Use the new API endpoint
                $response = Http::withHeaders([])->withOptions(['verify' => (app()->environment() == 'local') ? false : true])->timeout(800)
                    ->get(
                        'https://worker-embedding-mag.prime-42b.workers.dev',
                        [
                            'query' => $embedding_query,
                        ]
                    );

                if (! $response->successful()) {
                    throw new Exception('Embedding response failed, API error');
                }

                $embedding_response = json_decode($response->body(), true);

                try {
                    $embedding = new Vector($embedding_response['response']['data'][0]);

                    // dump($embedding);
                    // dump($embedding_query);

                    KeywordEmbedding::create([
                        'keyword' => $embedding_query,
                        'embedding' => $embedding,
                    ]);

                    break;
                } catch (Exception $e) {
                    throw new Exception('Embedding response failed, null response');
                }
            } catch (Exception $e) {
                $currentAttempt++;
                if ($currentAttempt >= $maxRetries) {
                    throw $e;
                    // we can throw exception here
                }
                // Optional: Add sleep for a few seconds if you want to delay the next attempt
                // sleep(1);
            }
        }
    }
}
