import { handleOpenAIError } from "./Errors.js";
import { Capabilities } from "./Capabilities.js";
import { DEFAULT_MODELS } from "../../constants.js";
import { buildUrl } from "./utils.js";
import { logger } from "../../utils/logger.js";
import { fetchWithTimeout } from "../../utils/fetch.js";
export class OpenAIEmbedding {
    baseUrl;
    apiKey;
    constructor(baseUrl, apiKey) {
        this.baseUrl = baseUrl;
        this.apiKey = apiKey;
    }
    getProviderName() {
        return "openai";
    }
    validateModel(model) {
        if (Capabilities.getModelType(model) !== "embeddings") {
            throw new Error(`Model ${model} does not support embeddings.`);
        }
    }
    async execute(request) {
        const model = request.model || DEFAULT_MODELS.EMBEDDING;
        this.validateModel(model);
        const body = {
            input: request.input,
            model
        };
        if (request.dimensions) {
            body.dimensions = request.dimensions;
        }
        if (request.user) {
            body.user = request.user;
        }
        const url = buildUrl(this.baseUrl, "/embeddings");
        logger.logRequest("OpenAI", "POST", url, body);
        const response = await fetchWithTimeout(url, {
            method: "POST",
            headers: {
                Authorization: `Bearer ${this.apiKey}`,
                "Content-Type": "application/json"
            },
            body: JSON.stringify(body)
        }, request.requestTimeout);
        if (!response.ok) {
            await handleOpenAIError(response, request.model || DEFAULT_MODELS.EMBEDDING);
        }
        const { data, model: responseModel, usage } = await response.json();
        logger.logResponse("OpenAI", response.status, response.statusText, {
            data,
            model: responseModel,
            usage
        });
        // Extract vectors from the response
        const vectors = data.map((item) => item.embedding);
        return {
            vectors,
            model: responseModel,
            input_tokens: usage.prompt_tokens,
            dimensions: vectors[0]?.length || 0
        };
    }
}
