import { ot as ensureAuthProfileStore } from "./model-selection-CMHF17-l.js";
import fs from "node:fs";
import path from "node:path";
import { AuthStorage, AuthStorage as AuthStorage$1, ModelRegistry, ModelRegistry as ModelRegistry$1 } from "@mariozechner/pi-coding-agent";

//#region ../../src/agents/pi-model-discovery.ts
function pickPiCompatibleProfileId(store, provider) {
	const providerProfiles = Object.entries(store.profiles).filter(([, credential]) => credential.provider === provider).map(([profileId]) => profileId);
	if (providerProfiles.length === 0) return;
	const preferred = store.order?.[provider]?.find((profileId) => providerProfiles.includes(profileId));
	if (preferred) return preferred;
	const defaultProfileId = `${provider}:default`;
	if (providerProfiles.includes(defaultProfileId)) return defaultProfileId;
	return providerProfiles.toSorted((a, b) => a.localeCompare(b))[0];
}
function buildPiApiKeyFromCredential(credential) {
	if (credential.type === "api_key") return credential.key?.trim() || null;
	if (credential.type === "token") {
		const token = credential.token?.trim();
		if (!token || typeof credential.expires === "number" && Number.isFinite(credential.expires) && credential.expires > 0 && Date.now() >= credential.expires) return null;
		return token;
	}
	const access = credential.access?.trim();
	if (!access || Date.now() >= credential.expires) return null;
	if (credential.provider === "google-gemini-cli" || credential.provider === "google-antigravity") return JSON.stringify({
		token: access,
		projectId: credential.projectId
	});
	return access;
}
function toPiAuthCredential(credential) {
	const key = buildPiApiKeyFromCredential(credential);
	if (!key) return null;
	return {
		type: "api_key",
		key
	};
}
function materializePiAuthJson(agentDir) {
	const authPath = path.join(agentDir, "auth.json");
	const store = ensureAuthProfileStore(agentDir, { allowKeychainPrompt: false });
	const providers = new Set(Object.values(store.profiles).map((credential) => credential.provider?.trim()).filter((provider) => Boolean(provider)));
	const piAuth = {};
	for (const provider of providers) {
		const profileId = pickPiCompatibleProfileId(store, provider);
		if (!profileId) continue;
		const credential = store.profiles[profileId];
		if (!credential) continue;
		const piCredential = toPiAuthCredential(credential);
		if (!piCredential) continue;
		piAuth[provider] = piCredential;
	}
	fs.mkdirSync(agentDir, {
		recursive: true,
		mode: 448
	});
	fs.writeFileSync(authPath, `${JSON.stringify(piAuth, null, 2)}\n`, { mode: 384 });
	return authPath;
}
function discoverAuthStorage(agentDir) {
	return new AuthStorage(materializePiAuthJson(agentDir));
}
function discoverModels(authStorage, agentDir) {
	return new ModelRegistry(authStorage, path.join(agentDir, "models.json"));
}

//#endregion
export { discoverModels as i, ModelRegistry$1 as n, discoverAuthStorage as r, AuthStorage$1 as t };