<?php

namespace App\Services;

use \Probots\Pinecone\Client as Pinecone;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class PineconeService
{
    protected $pinecone;
    protected $indexName;

    public function __construct()
    {
        $apiKey = config('pinecone.api_key');
        $indexHost = 'https://dbjkk-index-akk56kx.svc.aped-4627-b74a.pinecone.io';

        if (empty($apiKey)) {
            throw new \RuntimeException('Pinecone API key is not configured');
        }

        $this->pinecone = new Pinecone($apiKey, $indexHost);
    }

    public function upsert(array $vectors)
    {
        try {
            $response = $this->pinecone->data()->vectors()->upsert($vectors);
            if($response->successful()) {
                Log::info("Data Upsert Complete");
                return true;
            }
            Log::error("Data Upsert Failed", ['response' => $response]);
            return false;
        } catch (\Exception $e) {
            Log::error("Data Upsert Exception", ['error' => $e->getMessage()]);
            throw $e;
        }
    }

    public function query(array $queryOptions): array
    {
        try {
            $response = $this->pinecone->data()->vectors()->query($queryOptions);
            
            if($response->successful()) {
                return $response->json();
            }
            
            Log::error("Query Failed", ['response' => $response]);
            throw new \RuntimeException('Pinecone query failed');
        } catch (\Exception $e) {
            Log::error("Query Exception", ['error' => $e->getMessage()]);
            throw $e;
        }
    }

    public function deleteAllVectors(): bool
    {
        try {
            $response = $this->pinecone->data()->vectors()->delete(
                deleteAll: true
            );
            
            if($response->successful()) {
                Log::info("Data Removal Complete");
                return true;
            }
            
            Log::error("Data Removal Failed", ['response' => $response]);
            return false;
        } catch (\Exception $e) {
            Log::error("Data Removal Exception", ['error' => $e->getMessage()]);
            return true;
        }
    }
}