import { getApiKeyFromEnv, init_env_keys } from "../../../providers/env-keys.js";
import { CredentialResolver, init_credentials } from "../../../auth/credentials.js";
import { getModelsByProvider, getProviderDisplayName, getSortedProviders, init_providers, providerSupportsApiKey, providerSupportsOAuth } from "../../../providers/index.js";
import { listProfilesForProvider, upsertAuthProfile } from "../../../auth/profiles/profiles.js";
import { colors } from "../../utils/colors.js";
import { getOAuthProvider } from "../../utils/oauth-providers.js";
import { confirm, input, select } from "@inquirer/prompts";
//#region src/cli/commands/onboard/model.ts
/**
* Model Configuration for Onboarding
*/
init_providers();
init_credentials();
init_env_keys();
/**
* Get available models for a provider
*/
async function getModelsForProvider(provider) {
	return getModelsByProvider(provider).map((m) => ({
		value: `${m.provider}/${m.id}`,
		name: m.name || m.id
	}));
}
/**
* Perform OAuth login for a provider
*/
async function doOAuthLogin(provider) {
	const config = getOAuthProvider(provider);
	if (!config) {
		console.error(`OAuth not supported for provider: ${provider}`);
		return false;
	}
	console.log(`\n🔐 Starting ${config.displayName} OAuth login...`);
	const callbacks = {
		onAuth: (info) => {
			console.log(`\n${config.urlPrompt}`);
			console.log(info.url);
			if (info.instructions) console.log("\n" + info.instructions);
			console.log("\n");
		},
		onPrompt: async (prompt) => {
			return input({ message: prompt.message });
		},
		onProgress: (message) => {
			console.log(" →", message);
		}
	};
	try {
		const creds = await config.provider.login(callbacks);
		upsertAuthProfile({
			profileId: config.profileId,
			credential: {
				type: "oauth",
				provider,
				...creds
			}
		});
		return true;
	} catch (error) {
		console.error("❌ OAuth login failed:", error);
		return false;
	}
}
/**
* Configure AI model provider and model
*/
async function setupModel(existingConfig, ctx) {
	console.log("\n🤖 Step: AI Model\n");
	const config = existingConfig || {};
	const currentModelConfig = config?.agents?.defaults?.model;
	const currentModel = typeof currentModelConfig === "string" ? currentModelConfig : currentModelConfig?.primary;
	if (currentModel) {
		console.log("Current model:", currentModel);
		if (await confirm({
			message: "Keep using this model?",
			default: true
		})) {
			console.log("✅ Keeping:", currentModel);
			return config;
		}
	}
	const provider = await select({
		message: "Select provider:",
		choices: getSortedProviders().map((p) => ({
			value: p,
			name: getProviderDisplayName(p)
		}))
	});
	const providerName = getProviderDisplayName(provider);
	if (listProfilesForProvider(provider).length > 0) {
		console.log(`\n${colors.green("✓")} Found existing credentials for ${providerName}`);
		if (await confirm({
			message: "Use existing credentials?",
			default: true
		})) {
			const modelChoices = await getModelsForProvider(provider);
			if (modelChoices.length === 0) console.log(`\n⚠️  No models found for ${providerName}. Please check your credentials.`);
			else {
				const model = await select({
					message: "Select model:",
					choices: modelChoices
				});
				config.agents = config.agents || {};
				config.agents.defaults = config.agents.defaults || {
					workspace: ctx.workspacePath,
					model: {
						primary: model,
						fallbacks: []
					},
					maxTokens: 8192,
					temperature: .7,
					maxToolIterations: 20,
					maxRequestsPerTurn: 50,
					maxToolFailuresPerTurn: 3
				};
				config.agents.defaults.model = {
					primary: model,
					fallbacks: []
				};
				config.agents.defaults.workspace = ctx.workspacePath;
				console.log("\n✅ Model configured:", model);
				return config;
			}
		}
	}
	let apiKey;
	let useOAuth = false;
	apiKey = getApiKeyFromEnv(provider);
	if (apiKey) console.log(`\n${colors.green("✓")} Found API key for ${providerName} in environment`);
	if (!apiKey) {
		const supportsOAuth = providerSupportsOAuth(provider);
		const supportsApiKey = providerSupportsApiKey(provider);
		if (supportsOAuth && !supportsApiKey) if (await doOAuthLogin(provider)) {
			useOAuth = true;
			console.log("\n✅ OAuth login successful!");
		} else {
			console.error("\n❌ OAuth login failed. This provider requires OAuth.");
			return config;
		}
		else if (supportsOAuth && supportsApiKey) if (await select({
			message: `How would you like to authenticate with ${providerName}?`,
			choices: [{
				value: "api_key",
				name: "API Key (enter manually)"
			}, {
				value: "oauth",
				name: "OAuth Login (browser-based)"
			}]
		}) === "oauth") if (await doOAuthLogin(provider)) {
			useOAuth = true;
			console.log("\n✅ OAuth login successful!");
		} else {
			console.log("\n⚠️ OAuth login failed. Please enter API key manually.");
			apiKey = await input({
				message: `API Key for ${providerName}:`,
				validate: (v) => v.length > 0 || "Required"
			});
			useOAuth = false;
		}
		else apiKey = await input({
			message: `API Key for ${providerName}:`,
			validate: (v) => v.length > 0 || "Required"
		});
		else apiKey = await input({
			message: `API Key for ${providerName}:`,
			validate: (v) => v.length > 0 || "Required"
		});
	}
	const modelChoices = await getModelsForProvider(provider);
	if (modelChoices.length === 0) {
		console.log(`\n⚠️  No built-in models found for ${providerName}.`);
		console.log("   You can still use custom model names.");
		const model = await input({
			message: "Model name:",
			validate: (v) => v.length > 0 || "Required"
		});
		if (apiKey) await new CredentialResolver().saveApiKey(provider, apiKey, { profileName: "default" });
		config.agents = config.agents || {};
		config.agents.defaults = config.agents.defaults || {
			workspace: ctx.workspacePath,
			model: {
				primary: `${provider}/${model}`,
				fallbacks: []
			},
			maxTokens: 8192,
			temperature: .7,
			maxToolIterations: 20,
			maxRequestsPerTurn: 50,
			maxToolFailuresPerTurn: 3
		};
		config.agents.defaults.model = {
			primary: `${provider}/${model}`,
			fallbacks: []
		};
		config.agents.defaults.workspace = ctx.workspacePath;
		console.log("\n✅ Model configured:", `${provider}/${model}`);
		return config;
	}
	console.log(`\n📋 Available models for ${providerName}:`);
	const model = await select({
		message: "Select model:",
		choices: modelChoices
	});
	if (!useOAuth && apiKey) await new CredentialResolver().saveApiKey(provider, apiKey, { profileName: "default" });
	config.agents = config.agents || {};
	config.agents.defaults = config.agents.defaults || {
		workspace: ctx.workspacePath,
		model: {
			primary: model,
			fallbacks: []
		},
		maxTokens: 8192,
		temperature: .7,
		maxToolIterations: 20,
		maxRequestsPerTurn: 50,
		maxToolFailuresPerTurn: 3
	};
	config.agents.defaults.model = {
		primary: model,
		fallbacks: []
	};
	config.agents.defaults.workspace = ctx.workspacePath;
	console.log("\n✅ Model configured:", model);
	return config;
}
//#endregion
export { setupModel };

//# sourceMappingURL=model.js.map