export type Config = {
	apiKey: string;
	baseURL: string;
	model: string;
};

const DEFAULT_MODEL = "gemini-3.0-pro-image-landscape";

function getRequiredEnv(primaryName: string, fallbackName?: string): string {
	const primaryValue = Bun.env[primaryName]?.trim();

	if (primaryValue) {
		return primaryValue;
	}

	if (fallbackName) {
		const fallbackValue = Bun.env[fallbackName]?.trim();

		if (fallbackValue) {
			return fallbackValue;
		}
	}

	throw new Error(
		`Missing required environment variable: ${primaryName}${fallbackName ? ` (or ${fallbackName})` : ""}`,
	);
}

export function normalizeBaseUrl(baseURL: string): string {
	const url = new URL(baseURL);

	if (url.pathname === "" || url.pathname === "/") {
		url.pathname = "/v1";
	}

	return url.toString().replace(/\/$/, "");
}

export function loadConfig(): Config {
	return {
		apiKey: getRequiredEnv("FLOW2API_API_KEY", "OPENAI_API_KEY"),
		baseURL: normalizeBaseUrl(
			getRequiredEnv("FLOW2API_BASE_URL", "OPENAI_BASE_URL"),
		),
		model:
			Bun.env.FLOW2API_MODEL?.trim() ||
			Bun.env.GEMINI_MODEL?.trim() ||
			Bun.env.OPENAI_MODEL?.trim() ||
			DEFAULT_MODEL,
	};
}
