<?php
declare(strict_types=1);

namespace App\Service;

use Cake\Http\Client;

class EmbeddingsClient
{
    private Client $http;
    private string $apiKey;
    private string $model;

    public function __construct(
        ?Client $http = null,
        ?string $apiKey = null,
        ?string $model = null
    ) {
        $this->http  = $http ?? new Client(['timeout' => 30]);
        $this->apiKey = $apiKey ?? (string)env('OPENAI_API_KEY', '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');
        $this->model  = $model  ?? (string)env('OPENAI_EMBED_MODEL', 'text-embedding-3-small');
        if ($this->apiKey === '') {
            throw new \RuntimeException('OPENAI_API_KEY not set');
        }
    }

    /** @return float[] */
    public function embed(string $text): array
    {
        $res = $this->http->post(
            'https://api.openai.com/v1/embeddings',
            ['model' => $this->model, 'input' => $text],
            ['type' => 'json', 'headers' => [
                'Authorization' => 'Bearer ' . $this->apiKey,
                'Content-Type'  => 'application/json',
            ]]
        );
        if (!$res->isOk()) {
            throw new \RuntimeException('Embeddings API error: ' . $res->getStatusCode() . ' ' . $res->getStringBody());
        }
        $data = $res->getJson();
        return $data['data'][0]['embedding'] ?? [];
    }
}
