import assert from "node:assert/strict";
import { afterEach, test } from "vitest";

import { loadGatewayConfigFromEnv } from "../memory-embeddings-llm-gateway.js";

const KEYS = [
	"SF_LLM_GATEWAY_KEY",
	"SF_LLM_GATEWAY_URL",
	"SF_LLM_GATEWAY_EMBED_MODEL",
	"SF_LLM_GATEWAY_RERANK_MODEL",
	"LLM_GATEWAY_API_KEY",
	"LLM_GATEWAY_BEARER_KEY",
	"LLM_GATEWAY_BASE_URL",
	"LLM_MUX_API_KEY",
	"LLM_MUX_BASE_URL",
];

function withCleanGatewayEnv(fn) {
	const original = Object.fromEntries(
		KEYS.map((key) => [key, process.env[key]]),
	);
	for (const key of KEYS) delete process.env[key];
	afterEach(() => {
		for (const key of KEYS) {
			if (original[key] === undefined) delete process.env[key];
			else process.env[key] = original[key];
		}
	});
	fn();
}

test("loadGatewayConfigFromEnv accepts SF-prefixed configuration", () => {
	withCleanGatewayEnv(() => {
		process.env.SF_LLM_GATEWAY_KEY = "sf-key";
		process.env.SF_LLM_GATEWAY_URL = "https://example.test/v1";
		process.env.SF_LLM_GATEWAY_EMBED_MODEL = "embed-model";
		process.env.SF_LLM_GATEWAY_RERANK_MODEL = "rerank-model";

		assert.deepEqual(loadGatewayConfigFromEnv(), {
			url: "https://example.test/v1",
			apiKey: "sf-key",
			keySource: "SF_LLM_GATEWAY_KEY",
			urlSource: "SF_LLM_GATEWAY_URL",
			embeddingModel: "embed-model",
			rerankModel: "rerank-model",
		});
	});
});

test("loadGatewayConfigFromEnv accepts llm-gateway shell aliases", () => {
	withCleanGatewayEnv(() => {
		process.env.LLM_GATEWAY_BEARER_KEY = "gateway-key";
		process.env.LLM_GATEWAY_BASE_URL = "https://llm-gateway.test/v1";

		assert.deepEqual(loadGatewayConfigFromEnv(), {
			url: "https://llm-gateway.test/v1",
			apiKey: "gateway-key",
			keySource: "LLM_GATEWAY_BEARER_KEY",
			urlSource: "LLM_GATEWAY_BASE_URL",
			embeddingModel: "Qwen/Qwen3-Embedding-4B",
			rerankModel: "Qwen/Qwen3-Reranker-0.6B",
		});
	});
});

test("loadGatewayConfigFromEnv returns null without any gateway key", () => {
	withCleanGatewayEnv(() => {
		assert.equal(loadGatewayConfigFromEnv(), null);
	});
});
