import { _ as applySchema, b as paths, c as generateCodeChallenge, g as vaultStore, h as saveConfig, l as generateCodeVerifier, m as loadConfig, o as buildAuthorizationUrl, p as ensureConfigDir, s as exchangeAuthorizationCode, u as storeOAuthTokens, v as closeDatabase, y as openDatabase } from "./index.mjs";
import { a as R, c as We, d as Ct, i as Ne, l as Ze, n as Je, o as Re, r as Le, s as Ve, t as He, u as bt } from "./dist-BFgk1-yR.mjs";
import { a as formatPresetSummary, i as detectMcpClients, n as generateDaemonService, o as getModelPreset, r as registerMcpInAllClients, t as validateCredential } from "./validate-DxDJSvmm.mjs";

//#region src/setup/detect-local-providers.ts
const LOCAL_PROVIDERS = [
	{
		name: "Ollama",
		baseUrl: "http://localhost:11434"
	},
	{
		name: "LM Studio",
		baseUrl: "http://localhost:1234"
	},
	{
		name: "Open WebUI",
		baseUrl: "http://localhost:3000"
	}
];
async function isReachable(baseUrl) {
	try {
		return (await fetch(`${baseUrl}/v1/models`, { signal: AbortSignal.timeout(3e3) })).ok;
	} catch {
		try {
			const response = await fetch(baseUrl, { signal: AbortSignal.timeout(3e3) });
			return response.ok || response.status === 404;
		} catch {
			return false;
		}
	}
}
async function detectLocalProviders() {
	return await Promise.all(LOCAL_PROVIDERS.map(async (p) => ({
		name: p.name,
		baseUrl: p.baseUrl,
		running: await isReachable(p.baseUrl)
	})));
}

//#endregion
//#region src/auth/onboard-providers.ts
function handleCancel() {
	Ne("Setup cancelled.");
	process.exit(0);
}
async function chooseConnectionMode() {
	const mode = await Je({
		message: "How do you want to connect your AI?",
		options: [
			{
				value: "claude_subscription",
				label: "I have a Claude subscription",
				hint: "Pro/Max — login with your account"
			},
			{
				value: "api_key",
				label: "I have an API key",
				hint: "Anthropic, OpenAI, Google, etc."
			},
			{
				value: "local",
				label: "I run models locally",
				hint: "Ollama, LM Studio, Open WebUI"
			}
		]
	});
	if (Ct(mode)) handleCancel();
	return mode;
}
async function setupClaudeSubscription() {
	const verifier = generateCodeVerifier();
	const url = buildAuthorizationUrl(generateCodeChallenge(verifier), crypto.randomUUID());
	Ve(`Open this URL in your browser:\n\n${url}\n\nLog in with your Claude account.
After authorizing, copy the code shown on screen.`, "Login with Claude");
	const code = await Ze({
		message: "Paste the authorization code:",
		validate: (v) => !v || v.length < 10 ? "Code seems too short" : void 0
	});
	if (Ct(code)) handleCancel();
	const s = bt();
	s.start("Logging in...");
	const tokens = await exchangeAuthorizationCode(code, verifier);
	await storeOAuthTokens("anthropic", tokens);
	s.stop("Logged in successfully.");
	return {
		provider: "anthropic",
		authMethod: "oauth",
		credential: tokens.access_token
	};
}
async function setupApiKey() {
	const provider = await Je({
		message: "Which provider?",
		options: [
			{
				value: "anthropic",
				label: "Anthropic",
				hint: "Claude"
			},
			{
				value: "openai",
				label: "OpenAI",
				hint: "GPT-4o"
			},
			{
				value: "google",
				label: "Google",
				hint: "Gemini"
			}
		]
	});
	if (Ct(provider)) handleCancel();
	const key = await He({
		message: `Enter your ${provider} API key:`,
		validate: (v) => !v || v.length < 8 ? "API key seems too short" : void 0
	});
	if (Ct(key)) handleCancel();
	const s = bt();
	s.start("Validating...");
	const result = await validateCredential(provider, key);
	if (result.isValid) s.stop(`Valid: ${result.accountInfo ?? "OK"}`);
	else {
		s.stop(`Warning: ${result.error ?? "Could not validate"}`);
		const proceed = await Re({
			message: "Continue anyway?",
			initialValue: false
		});
		if (Ct(proceed) || !proceed) handleCancel();
	}
	const vs = bt();
	vs.start("Encrypting credentials...");
	await vaultStore(`${provider}-api-key`, key);
	vs.stop("Credentials stored in encrypted vault.");
	return {
		provider,
		authMethod: "encrypted_file",
		credential: key
	};
}
async function setupLocal() {
	const s = bt();
	s.start("Scanning for local AI providers...");
	const running = (await detectLocalProviders()).filter((l) => l.running);
	s.stop(running.length > 0 ? `Found: ${running.map((l) => l.name).join(", ")}` : "No local provider detected.");
	let provider;
	let baseUrl;
	if (running.length === 1) {
		provider = running[0].name.toLowerCase().replace(/\s+/g, "-");
		baseUrl = running[0].baseUrl;
		R.info(`Using ${running[0].name} at ${baseUrl}`);
	} else if (running.length > 1) {
		const choice = await Je({
			message: "Multiple providers detected. Which one?",
			options: running.map((l) => ({
				value: l.baseUrl,
				label: l.name,
				hint: l.baseUrl
			}))
		});
		if (Ct(choice)) handleCancel();
		baseUrl = choice;
		const match = running.find((l) => l.baseUrl === choice);
		provider = match ? match.name.toLowerCase().replace(/\s+/g, "-") : "ollama";
	} else {
		R.warn("No local provider is running.");
		const choice = await Je({
			message: "Which provider will you use?",
			options: [
				{
					value: "ollama",
					label: "Ollama",
					hint: "localhost:11434"
				},
				{
					value: "lm-studio",
					label: "LM Studio",
					hint: "localhost:1234"
				},
				{
					value: "open-webui",
					label: "Open WebUI",
					hint: "localhost:3000"
				}
			]
		});
		if (Ct(choice)) handleCancel();
		provider = choice;
		baseUrl = {
			ollama: "http://localhost:11434",
			"lm-studio": "http://localhost:1234",
			"open-webui": "http://localhost:3000"
		}[provider] ?? "http://localhost:11434";
		R.info(`Start ${provider} before running Sauria.`);
	}
	await vaultStore("local-base-url", baseUrl);
	return {
		provider,
		authMethod: "none",
		credential: ""
	};
}

//#endregion
//#region src/auth/onboard.ts
async function runPostSetup(provider, authMethod, preset) {
	const mcpSpin = bt();
	mcpSpin.start("Connecting to your AI clients...");
	const clients = detectMcpClients();
	const detected = clients.filter((c) => c.detected);
	if (detected.length > 0) {
		const results = registerMcpInAllClients(clients);
		const registered = results.filter((r) => r.status === "registered");
		const already = results.filter((r) => r.status === "already_registered");
		const parts = [];
		if (registered.length > 0) parts.push(registered.map((r) => r.client).join(", "));
		if (already.length > 0) parts.push(`already: ${already.map((r) => r.client).join(", ")}`);
		mcpSpin.stop(`Connected: ${parts.join(" | ")}`);
	} else mcpSpin.stop("No AI clients detected.");
	const daemonSpin = bt();
	daemonSpin.start("Setting up background service...");
	const daemon = generateDaemonService();
	if (daemon) daemonSpin.stop(`Daemon ready (${daemon.platform}).`);
	else daemonSpin.stop("Daemon: run `sauria daemon` manually.");
	const lines = [
		`Provider:    ${provider} (${authMethod})`,
		formatPresetSummary(preset),
		`Database:    ${paths.db}`
	];
	if (detected.length > 0) lines.push(`AI clients:  ${detected.map((c) => c.name).join(", ")}`);
	Ve(lines.join("\n"), "Setup Complete");
	if (detected.length > 0) Le("Restart your AI client and Sauria is ready.");
	else Le("Run `sauria daemon` to start.");
}
async function runOnboarding() {
	We("Welcome to Sauria");
	const mode = await chooseConnectionMode();
	let provider;
	let authMethod;
	if (mode === "claude_subscription") {
		const result = await setupClaudeSubscription();
		provider = result.provider;
		authMethod = result.authMethod;
	} else if (mode === "api_key") {
		const result = await setupApiKey();
		provider = result.provider;
		authMethod = result.authMethod;
	} else {
		const result = await setupLocal();
		provider = result.provider;
		authMethod = result.authMethod;
	}
	const initSpin = bt();
	initSpin.start("Initializing...");
	await ensureConfigDir();
	const db = openDatabase();
	applySchema(db);
	closeDatabase(db);
	initSpin.stop("Ready.");
	const preset = getModelPreset(provider);
	const config = await loadConfig();
	await saveConfig({
		...config,
		models: { ...preset },
		auth: {
			...config.auth,
			[provider]: { method: authMethod }
		}
	});
	await runPostSetup(provider, authMethod, preset);
}

//#endregion
export { runOnboarding };
//# sourceMappingURL=onboard-8gPyGDK-.mjs.map