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

use boru\ai\Config\Config;
use boru\ai\Embedding\ArrayEmbeddingStore;
use boru\ai\Embedding\EmbeddingRequest;
use boru\ai\Embedding\EmbeddingService;
use boru\ai\Provider\ProviderRegistry;
use boru\ai\Tests\Fakes\FakeProvider;
use PHPUnit\Framework\TestCase;

class EmbeddingServiceTest extends TestCase
{
    public function testEmbedReadsAndWritesCacheByDefault()
    {
        $provider = new FakeProvider();
        $registry = new ProviderRegistry();
        $registry->register($provider);
        $registry->mapModelPrefix('fake-', 'fake');

        $config = new Config();
        $config->provider('fake', array(
            'vector' => array(
                'model' => 'fake-embedding-1',
            ),
        ));

        $service = new EmbeddingService($registry, new ArrayEmbeddingStore(), $config);

        $request = new EmbeddingRequest();
        $request->provider('fake');
        $request->input('hello world');

        $first = $service->embed($request);
        $second = $service->embed($request);

        $this->assertFalse($first->cacheHit());
        $this->assertTrue($second->cacheHit());
        $this->assertSame(1, $provider->embedCalls);
        $this->assertSame($first->vector(), $second->vector());
    }

    public function testEmbedCanDisableCacheReadPerRequest()
    {
        $provider = new FakeProvider();
        $registry = new ProviderRegistry();
        $registry->register($provider);

        $config = new Config();
        $config->provider('fake', array(
            'vector' => array(
                'model' => 'fake-embedding-1',
            ),
        ));

        $service = new EmbeddingService($registry, new ArrayEmbeddingStore(), $config);

        $request = new EmbeddingRequest();
        $request->provider('fake');
        $request->input('hello');

        $service->embed($request);

        $requestNoRead = $request->copy();
        $requestNoRead->option('cache_read', false);

        $result = $service->embed($requestNoRead);

        $this->assertFalse($result->cacheHit());
        $this->assertSame(2, $provider->embedCalls);
    }
}
