<?php
namespace boru\ai\Embedding;

class ArrayEmbeddingStore implements EmbeddingStoreInterface
{
    /** @var array */
    protected $entries = array();

    public function findResult($cacheKey)
    {
        if (!isset($this->entries[$cacheKey])) {
            return false;
        }

        $entry = $this->entries[$cacheKey];
        if (isset($entry['expires_at']) && $entry['expires_at'] !== null && $entry['expires_at'] < time()) {
            unset($this->entries[$cacheKey]);
            return false;
        }

        return EmbeddingResult::fromArray($entry['result']);
    }

    public function saveResult($cacheKey, EmbeddingRequest $request, EmbeddingResult $result, $ttlSeconds = null)
    {
        $expiresAt = null;
        if ($ttlSeconds !== null) {
            $ttlSeconds = (int)$ttlSeconds;
            if ($ttlSeconds > 0) {
                $expiresAt = time() + $ttlSeconds;
            }
        }

        $this->entries[$cacheKey] = array(
            'request' => array(
                'provider' => $request->provider(),
                'model' => $request->model(),
                'inputs' => $request->inputs(),
                'options' => $request->option(),
            ),
            'result' => $result->toArray(),
            'expires_at' => $expiresAt,
        );

        return $result;
    }
}
