<?php
namespace boru\ai\Tests\Integration;

use boru\ai\AI;
use boru\ai\Persistence\Db\DbEmbeddingStore;
use boru\ai\Tests\Fakes\FakeHttpClient;

class DbBootstrapEmbeddingCacheIntegrationTest extends DbIntegrationTestCase
{
    public function testBootstrapEmbeddingFlowPersistsAndReusesDbCache()
    {
        $httpClient = new FakeHttpClient();
        $httpClient->queueResponse($this->jsonResponse(array(
            'model' => 'text-embedding-3-small',
            'data' => array(
                array(
                    'index' => 0,
                    'embedding' => array(0.5, 0.6, 0.7),
                ),
            ),
            'usage' => array(
                'prompt_tokens' => 3,
                'total_tokens' => 3,
            ),
        )));

        $config = $this->bootstrapWithDbPersistence($httpClient, null);
        $config->provider('openai', array(
            'vector' => array(
                'model' => 'text-embedding-3-small',
            ),
        ));

        $this->assertInstanceOf(DbEmbeddingStore::class, AI::embeddingStore());

        $first = AI::provider('openai')->embed('db cache me');
        $second = AI::provider('openai')->embed('db cache me');

        $this->assertFalse($first->cacheHit());
        $this->assertTrue($second->cacheHit());
        $this->assertSame(array(0.5, 0.6, 0.7), $second->vector());
        $this->assertCount(1, $httpClient->requests);
        $this->assertSame(1, $this->countRows($this->tableNames['embeddings']));

        $embeddingRow = $this->fetchOne('select * from `' . $this->tableNames['embeddings'] . '` order by `id` asc limit 1');
        $this->assertSame('openai', $embeddingRow->get('provider'));
        $this->assertSame('text-embedding-3-small', $embeddingRow->get('model'));
        $this->assertStringContainsString('db cache me', $embeddingRow->get('inputs_json'));
        $this->assertStringContainsString('0.5', $embeddingRow->get('result_json'));
    }
}
