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

use boru\ai\AI;
use boru\ai\Tests\Fakes\FakeHttpClient;

class BootstrapEmbeddingIntegrationTest extends IntegrationTestCase
{
    public function testBootstrapEmbeddingFlowUsesConfiguredCacheStoreAcrossCalls()
    {
        $httpClient = new FakeHttpClient();
        $httpClient->queueResponse($this->jsonResponse(array(
            'model' => 'text-embedding-3-small',
            'data' => array(
                array(
                    'index' => 0,
                    'embedding' => array(0.11, 0.22, 0.33),
                ),
            ),
            'usage' => array(
                'prompt_tokens' => 2,
                'total_tokens' => 2,
            ),
        )));

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

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

        $this->assertFalse($first->cacheHit());
        $this->assertTrue($second->cacheHit());
        $this->assertSame(array(0.11, 0.22, 0.33), $second->vector());
        $this->assertCount(1, $httpClient->requests);
        $this->assertSame('https://api.openai.com/v1/embeddings', $httpClient->requests[0]->url());
        $this->assertSame('cache me', $httpClient->requests[0]->json()['input']);
    }

    public function testEmbeddingRequestCanBypassCachePerCallThroughFacadeOptions()
    {
        $httpClient = new FakeHttpClient();
        $httpClient->queueResponse($this->jsonResponse(array(
            'model' => 'text-embedding-3-small',
            'data' => array(
                array(
                    'index' => 0,
                    'embedding' => array(1.0, 2.0),
                ),
            ),
        )));
        $httpClient->queueResponse($this->jsonResponse(array(
            'model' => 'text-embedding-3-small',
            'data' => array(
                array(
                    'index' => 0,
                    'embedding' => array(3.0, 4.0),
                ),
            ),
        )));

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

        $first = AI::provider('openai')->embed('cache control');
        $second = AI::provider('openai')->embed('cache control', array(
            'cache_read' => false,
        ));

        $this->assertFalse($first->cacheHit());
        $this->assertFalse($second->cacheHit());
        $this->assertEquals(array(3.0, 4.0), $second->vector());
        $this->assertCount(2, $httpClient->requests);
    }
}
