import { __esmMin } from "../../_virtual/_rolldown/runtime.js";
import { init_paths, resolveAgentAuthProfilesPath, resolveAuthProfilesPath, resolveOAuthPath } from "../config/paths.js";
import { init_loader, loadConfig } from "../config/loader.js";
import { getDefaultAgentId, init_resolve_route } from "../routing/resolve-route.js";
import { existsSync, readFileSync } from "node:fs";
//#region src/auth/sync-provider-auth.ts
/**
* Synchronous checks that mirror CredentialResolver.resolveApiKey sources
* used by isProviderConfiguredSync (fallback candidate filtering).
*/
function findProfileForProvider(file, provider) {
	const normalizedProvider = provider.toLowerCase();
	for (const [, profile] of Object.entries(file.profiles)) if (profile.provider === normalizedProvider) return profile;
	return null;
}
function profileHasUsableKey(profile) {
	if (profile.envVar) return !!(process.env[profile.envVar]?.trim() || profile.key?.trim());
	return !!profile.key?.trim();
}
function readAuthProfiles(path) {
	if (!existsSync(path)) return null;
	try {
		const data = JSON.parse(readFileSync(path, "utf-8"));
		return {
			version: data.version ?? 1,
			profiles: data.profiles ?? {}
		};
	} catch {
		return null;
	}
}
function hasApiKeyInProfilesFile(path, provider) {
	const file = readAuthProfiles(path);
	if (!file) return false;
	const profile = findProfileForProvider(file, provider);
	return profile ? profileHasUsableKey(profile) : false;
}
function hasOAuthTokenSync(provider) {
	const oauthPath = resolveOAuthPath(provider.toLowerCase());
	if (!existsSync(oauthPath)) return false;
	try {
		const token = JSON.parse(readFileSync(oauthPath, "utf-8"));
		if (!token.access?.trim()) return false;
		if (token.expiresAt && token.expiresAt < Date.now()) return false;
		return true;
	} catch {
		return false;
	}
}
/** Same resolution order as {@link CredentialResolver.loadFromAgentCredentials} / global profile (envVar then key). */
function resolveProfileSecret(profile) {
	if (profile.envVar) {
		const fromEnv = process.env[profile.envVar]?.trim();
		if (fromEnv) return fromEnv;
	}
	if (profile.key?.trim()) return profile.key.trim();
}
function readApiKeyFromProfilesFile(path, provider) {
	const file = readAuthProfiles(path);
	if (!file) return void 0;
	const profile = findProfileForProvider(file, provider);
	if (!profile) return void 0;
	return resolveProfileSecret(profile);
}
function readOAuthAccessTokenSync(provider) {
	const oauthPath = resolveOAuthPath(provider.toLowerCase());
	if (!existsSync(oauthPath)) return void 0;
	try {
		const token = JSON.parse(readFileSync(oauthPath, "utf-8"));
		if (!token.access?.trim()) return void 0;
		if (token.expiresAt && token.expiresAt < Date.now()) return void 0;
		return token.access.trim();
	} catch {
		return;
	}
}
/**
* Synchronous API key / OAuth access for {@link Agent} `getApiKey` (pi-agent requires sync).
* Order: default agent auth-profiles → global auth-profiles → OAuth token file.
* Does not read standard env vars or models.json registry — callers chain `getApiKeySync` after this.
*/
function resolveProviderApiKeySync(provider) {
	const normalized = provider.toLowerCase();
	const cfg = loadConfig();
	const fromAgent = readApiKeyFromProfilesFile(resolveAgentAuthProfilesPath(cfg, getDefaultAgentId(cfg)), normalized);
	if (fromAgent) return fromAgent;
	const fromGlobal = readApiKeyFromProfilesFile(resolveAuthProfilesPath(), normalized);
	if (fromGlobal) return fromGlobal;
	return readOAuthAccessTokenSync(normalized);
}
/**
* True if credentials exist in auth profiles (global or agent) or OAuth store,
* matching async CredentialResolver resolution (excluding env — callers check env separately).
*/
function hasProviderAuthOnDiskSync(provider) {
	const cfg = loadConfig();
	if (hasApiKeyInProfilesFile(resolveAgentAuthProfilesPath(cfg, getDefaultAgentId(cfg)), provider)) return true;
	if (hasApiKeyInProfilesFile(resolveAuthProfilesPath(), provider)) return true;
	if (hasOAuthTokenSync(provider)) return true;
	return false;
}
var init_sync_provider_auth = __esmMin((() => {
	init_paths();
	init_loader();
	init_resolve_route();
}));
//#endregion
init_sync_provider_auth();
export { hasProviderAuthOnDiskSync, init_sync_provider_auth, resolveProviderApiKeySync };

//# sourceMappingURL=sync-provider-auth.js.map