import assert from "node:assert/strict";
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, test } from "vitest";
import { resolveModelWithFallbacksForUnit } from "../preferences-models.js";
import { getConfiguredEnvApiKey } from "../provider-env-auth.js";

const originalCwd = process.cwd();
const originalEnv = { ...process.env };
const tmpDirs = [];

afterEach(() => {
	process.chdir(originalCwd);
	process.env = { ...originalEnv };
	while (tmpDirs.length > 0) {
		rmSync(tmpDirs.pop(), { recursive: true, force: true });
	}
});

function makePreferencesProject(projectPreferences, projectSettings) {
	const root = mkdtempSync(join(tmpdir(), "sf-preferences-models-"));
	tmpDirs.push(root);
	const home = join(root, "home");
	const project = join(root, "project");
	mkdirSync(join(home, ".sf", "agent"), { recursive: true });
	mkdirSync(join(project, ".sf"), { recursive: true });
	writeFileSync(
		join(project, ".sf", "PREFERENCES.md"),
		projectPreferences,
		"utf-8",
	);
	if (projectSettings) {
		writeFileSync(
			join(project, ".sf", "settings.json"),
			JSON.stringify(projectSettings, null, 2),
			"utf-8",
		);
	}
	process.env.HOME = home;
	process.chdir(project);
	return project;
}

describe("preferences model resolution", () => {
	test("resolveModelWithFallbacksForUnit_when_google_env_auth_is_default_off_skips_google_auto_benchmark_candidates", () => {
		makePreferencesProject(
			[
				"---",
				"version: 1",
				"allowed_providers:",
				"  - google",
				"models: {}",
				"---",
				"",
			].join("\n"),
		);
		process.env.GEMINI_API_KEY = "test-google-key";

		const result = resolveModelWithFallbacksForUnit("plan-milestone");

		assert.equal(result, undefined);
	});

	test("resolveModelWithFallbacksForUnit_when_google_env_auth_is_enabled_uses_google_auto_benchmark_candidates", () => {
		makePreferencesProject(
			[
				"---",
				"version: 1",
				"allowed_providers:",
				"  - google",
				"models: {}",
				"---",
				"",
			].join("\n"),
			{
				providerEnvAuth: {
					providers: {
						google: "on",
					},
				},
			},
		);
		process.env.GEMINI_API_KEY = "test-google-key";

		assert.equal(getConfiguredEnvApiKey("google"), "test-google-key");
		const result = resolveModelWithFallbacksForUnit("plan-milestone");

		assert.ok(result);
		assert.equal(typeof result.primary, "string");
		assert.ok(result.primary.length > 0);
	});
});
