import { existsSync, readFileSync } from "node:fs";
import { join } from "node:path";
import { getEnvApiKey } from "@singularity-forge/pi-ai";
import {
	getAgentDir,
	SettingsManager,
} from "@singularity-forge/pi-coding-agent";

const GOOGLE_ENV_AUTH_DEFAULT_OFF_PROVIDERS = new Set([
	"google",
	"google-gemini-cli",
]);

function readJson(path) {
	try {
		if (!existsSync(path)) return {};
		return JSON.parse(readFileSync(path, "utf-8"));
	} catch {
		return {};
	}
}

function readProviderEnvAuthSettings(cwd, agentDir) {
	const globalSettings = readJson(join(agentDir, "settings.json"));
	const projectSettings = readJson(join(cwd, ".sf", "settings.json"));
	return {
		...(globalSettings.providerEnvAuth ?? {}),
		...(projectSettings.providerEnvAuth ?? {}),
		providers: {
			...(globalSettings.providerEnvAuth?.providers ?? {}),
			...(projectSettings.providerEnvAuth?.providers ?? {}),
		},
	};
}

function getProviderEnvAuthMode(providerId, cwd) {
	const agentDir = getAgentDir();
	const settingsManager = SettingsManager.create(cwd, agentDir);
	if (typeof settingsManager.getProviderEnvAuthMode === "function") {
		return settingsManager.getProviderEnvAuthMode(providerId);
	}
	const settings = readProviderEnvAuthSettings(cwd, agentDir);
	return (
		settings.providers?.[providerId] ??
		settings.default ??
		(GOOGLE_ENV_AUTH_DEFAULT_OFF_PROVIDERS.has(providerId) ? "off" : "auto")
	);
}

function getProviderEnvKey(providerId) {
	const apiKey = getEnvApiKey(providerId);
	if (apiKey) return apiKey;
	if (providerId === "google") {
		return (
			process.env.GEMINI_API_KEY || process.env.GOOGLE_GENERATIVE_AI_API_KEY
		);
	}
	return undefined;
}

/**
 * Return the provider env API key only when Forge settings allow env auth.
 *
 * Purpose: keep SF extension-side provider heuristics aligned with the core
 * providerEnvAuth policy so ambient env keys do not bypass settings.json.
 *
 * Consumer: doctor-providers.js and preferences-models.js when checking whether
 * a provider is available from environment credentials.
 */
export function getConfiguredEnvApiKey(providerId, cwd = process.cwd()) {
	if (getProviderEnvAuthMode(providerId, cwd) === "off") return undefined;
	return getProviderEnvKey(providerId);
}
