import type { OAuthCredentials, OAuthLoginCallbacks, OAuthProviderInterface } from "./types.js";

/**
 * Venice AI API key provider.
 *
 * Venice uses API key authentication rather than OAuth, but implements
 * OAuthProviderInterface so it integrates cleanly with JAE's /login flow.
 *
 * Get your API key at: https://venice.ai/settings/api
 */
export async function loginVenice(callbacks: OAuthLoginCallbacks): Promise<OAuthCredentials> {
	callbacks.onProgress?.("To get an API key, visit https://venice.ai/settings/api");

	const apiKey = await callbacks.onPrompt({
		message: "Enter your Venice AI API key:",
		placeholder: "e.g. your_venice_api_key",
	});

	if (!apiKey || !apiKey.trim()) {
		throw new Error("No API key provided");
	}

	return {
		access: apiKey.trim(),
		refresh: "",
		// API keys don't expire — set a 10-year window so the refresh path is never hit
		expires: Date.now() + 1000 * 60 * 60 * 24 * 365 * 10,
	};
}

export async function refreshVeniceToken(credentials: OAuthCredentials): Promise<OAuthCredentials> {
	// API keys don't expire, just bump the expiry forward
	return {
		...credentials,
		expires: Date.now() + 1000 * 60 * 60 * 24 * 365 * 10,
	};
}

export const veniceOAuthProvider: OAuthProviderInterface = {
	id: "venice",
	name: "Venice AI (API Key)",

	async login(callbacks: OAuthLoginCallbacks): Promise<OAuthCredentials> {
		return loginVenice(callbacks);
	},

	async refreshToken(credentials: OAuthCredentials): Promise<OAuthCredentials> {
		return refreshVeniceToken(credentials);
	},

	getApiKey(credentials: OAuthCredentials): string {
		return credentials.access;
	},
};
