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58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
/**
 * mem0 init β€” interactive setup wizard.
 */

import fs from "node:fs";
import readline from "node:readline";
import { PlatformBackend } from "../backend/platform.js";
import {
	colors,
	printBanner,
	printError,
	printInfo,
	printSuccess,
} from "../branding.js";
import {
	CONFIG_FILE,
	DEFAULT_BASE_URL,
	type Mem0Config,
	createDefaultConfig,
	loadConfig,
	redactKey,
	saveConfig,
} from "../config.js";

const { brand, dim } = colors;

const EMAIL_RE = /^[^@\s]+@[^@\s]+\.[^@\s]+$/;

function validateEmail(email: string): void {
	if (!EMAIL_RE.test(email)) {
		printError(`Invalid email address: ${JSON.stringify(email)}`);
		process.exit(1);
	}
}

async function emailLogin(
	email: string,
	code: string | undefined,
	baseUrl: string,
): Promise<Record<string, unknown>> {
	const url = baseUrl.replace(/\/+$/, "");
	let codeValue = code;

	const sourceHeaders = {
		"Content-Type": "application/json",
		"X-Mem0-Source": "cli",
		"X-Mem0-Client-Language": "node",
	};

	if (!codeValue) {
		const resp = await fetch(`${url}/api/v1/auth/email_code/`, {
			method: "POST",
			headers: sourceHeaders,
			body: JSON.stringify({ email }),
			signal: AbortSignal.timeout(30_000),
		});
		if (resp.status === 429) {
			printError("Too many attempts. Try again in a few minutes.");
			process.exit(1);
		}
		if (!resp.ok) {
			let detail: string;
			try {
				const body = (await resp.json()) as Record<string, unknown>;
				detail = (body.error ?? body.detail ?? resp.statusText) as string;
			} catch {
				detail = resp.statusText;
			}
			printError(`Failed to send code: ${detail}`);
			process.exit(1);
		}

		printSuccess("Verification code sent! Check your email.");

		if (!process.stdin.isTTY) {
			printError(
				"No --code provided and terminal is non-interactive.",
				"Run: mem0 init --email <email> --code <code>",
			);
			process.exit(1);
		}

		console.log();
		const entered = await promptLine(`  ${brand("Verification Code")}`);
		if (!entered) {
			printError("Code is required.");
			process.exit(1);
		}
		codeValue = entered;
	}

	const verifyResp = await fetch(`${url}/api/v1/auth/email_code/verify/`, {
		method: "POST",
		headers: sourceHeaders,
		body: JSON.stringify({ email, code: codeValue.trim() }),
		signal: AbortSignal.timeout(30_000),
	});
	if (verifyResp.status === 429) {
		printError("Too many attempts. Try again in a few minutes.");
		process.exit(1);
	}
	if (!verifyResp.ok) {
		let detail: string;
		try {
			const body = (await verifyResp.json()) as Record<string, unknown>;
			detail = (body.error ?? body.detail ?? verifyResp.statusText) as string;
		} catch {
			detail = verifyResp.statusText;
		}
		printError(`Verification failed: ${detail}`);
		process.exit(1);
	}

	return verifyResp.json() as Promise<Record<string, unknown>>;
}

function promptSecret(label: string): Promise<string> {
	return new Promise((resolve, reject) => {
		process.stdout.write(label);

		if (process.stdin.isTTY) {
			process.stdin.setRawMode(true);
		}
		process.stdin.resume();
		process.stdin.setEncoding("utf-8");

		const chars: string[] = [];

		const onData = (key: string) => {
			for (const ch of key) {
				if (ch === "\r" || ch === "\n") {
					cleanup();
					process.stdout.write("\n");
					resolve(chars.join(""));
					return;
				}
				if (ch === "\x03") {
					cleanup();
					reject(new Error("Interrupted"));
					return;
				}
				if (ch === "\x7f" || ch === "\x08") {
					// backspace
					if (chars.length > 0) {
						chars.pop();
						process.stdout.write("\b \b");
					}
				} else if (ch === "\x15") {
					// Ctrl+U β€” clear line
					process.stdout.write("\b \b".repeat(chars.length));
					chars.length = 0;
				} else if (ch >= " ") {
					chars.push(ch);
					process.stdout.write("*");
				}
			}
		};

		const cleanup = () => {
			process.stdin.removeListener("data", onData);
			if (process.stdin.isTTY) {
				process.stdin.setRawMode(false);
			}
			process.stdin.pause();
		};

		process.stdin.on("data", onData);
	});
}

function promptLine(label: string, defaultValue?: string): Promise<string> {
	const rl = readline.createInterface({
		input: process.stdin,
		output: process.stdout,
	});
	const prompt = defaultValue ? `${label} [${defaultValue}]: ` : `${label}: `;
	return new Promise((resolve) => {
		rl.question(prompt, (answer) => {
			rl.close();
			resolve(answer.trim() || defaultValue || "");
		});
	});
}

async function setupPlatform(config: Mem0Config): Promise<void> {
	console.log();
	console.log(
		`  ${dim("Get your API key at https://app.mem0.ai/dashboard/api-keys")}`,
	);
	console.log();

	process.stdout.write(`  ${brand("API Key")}: `);
	const apiKey = await promptSecret("");
	if (!apiKey) {
		printError("API key is required.");
		process.exit(1);
	}
	config.platform.apiKey = apiKey;
}

async function setupDefaults(config: Mem0Config): Promise<void> {
	console.log();
	printInfo("Set default entity IDs (press Enter to skip).\n");

	const _systemUser = process.env.USER || process.env.USERNAME || "mem0-cli";
	const userId = await promptLine(
		`  ${brand("Default User ID")} ${dim("(recommended)")}`,
		_systemUser,
	);
	if (userId) config.defaults.userId = userId;
}

async function validatePlatform(config: Mem0Config): Promise<void> {
	console.log();
	printInfo("Validating connection...");
	try {
		const backend = new PlatformBackend(config.platform);
		const status = await backend.status({
			userId: config.defaults.userId || undefined,
			agentId: config.defaults.agentId || undefined,
		});
		if (status.connected) {
			printSuccess("Connected to mem0 Platform!");
			// Cache user_email from ping response for telemetry distinct_id
			try {
				const pingData = (await backend.ping()) as Record<string, unknown>;
				const userEmail = pingData?.user_email as string | undefined;
				if (userEmail) {
					config.platform.userEmail = userEmail;
				}
			} catch {
				/* ignore β€” telemetry ID will fall back to API key hash */
			}
		} else {
			printError(
				`Could not connect: ${status.error ?? "Unknown error"}`,
				"Visit https://app.mem0.ai/dashboard/api-keys to get a new key, or run mem0 init again.",
			);
		}
	} catch (e) {
		printError(`Connection test failed: ${e instanceof Error ? e.message : e}`);
	}
}

export async function runInit(
	opts: {
		apiKey?: string;
		userId?: string;
		email?: string;
		code?: string;
		force?: boolean;
	} = {},
): Promise<void> {
	const config = createDefaultConfig();
	const savedConfig = loadConfig();
	const baseUrl =
		process.env.MEM0_BASE_URL ||
		savedConfig.platform.baseUrl ||
		DEFAULT_BASE_URL;

	// Guards
	if (opts.code && !opts.email) {
		printError("--code requires --email.");
		process.exit(1);
	}
	if (opts.email && opts.apiKey) {
		printError("Cannot use both --api-key and --email.");
		process.exit(1);
	}

	// Warn if an existing config with an API key would be overwritten
	if (
		!opts.force &&
		fs.existsSync(CONFIG_FILE) &&
		savedConfig.platform.apiKey
	) {
		console.log(
			`\n  ${brand("Existing configuration found")} ${dim(`(API key: ${redactKey(savedConfig.platform.apiKey)})`)}`,
		);
		if (process.stdin.isTTY) {
			const rl = readline.createInterface({
				input: process.stdin,
				output: process.stdout,
			});
			const answer = await new Promise<string>((resolve) => {
				rl.question(
					"  Overwrite existing config? This cannot be undone. [y/N] ",
					resolve,
				);
			});
			rl.close();
			if (answer.toLowerCase() !== "y") {
				printInfo("Cancelled. Use --force to skip this check.");
				process.exit(0);
			}
		} else {
			printError(
				"Existing config would be overwritten.",
				"Use --force to overwrite.",
			);
			process.exit(1);
		}
	}

	// ── Email login flow ──────────────────────────────────────────────────────
	if (opts.email) {
		const email = opts.email.trim().toLowerCase();
		validateEmail(email);

		printBanner();
		console.log();
		printInfo(`Logging in as ${email}...\n`);

		const result = await emailLogin(email, opts.code, baseUrl);

		const apiKeyVal = result.api_key as string | undefined;
		if (!apiKeyVal) {
			printError(
				"Auth succeeded but no API key was returned. Contact support.",
			);
			process.exit(1);
		}

		config.platform.apiKey = apiKeyVal;
		config.platform.baseUrl = baseUrl;
		config.platform.userEmail = email;
		config.defaults.userId =
			opts.userId || process.env.USER || process.env.USERNAME || "mem0-cli";

		saveConfig(config);
		console.log();
		printSuccess("Authenticated! Configuration saved to ~/.mem0/config.json");
		console.log();
		console.log(`  ${dim("Get started:")}`);
		console.log(`  ${dim('  mem0 add "I prefer dark mode"')}`);
		console.log(`  ${dim('  mem0 search "preferences"')}`);
		console.log();
		return;
	}

	// ── API key flow ──────────────────────────────────────────────────────────

	// Non-TTY: resolve defaults so partial flags work in pipelines / CI
	if (!process.stdin.isTTY) {
		if (!opts.apiKey) {
			printError(
				"Non-interactive terminal detected and --api-key is required.",
				"Usage: mem0 init --api-key <key> [--user-id <id>]",
			);
			process.exit(1);
		}
		opts.userId =
			opts.userId || process.env.USER || process.env.USERNAME || "mem0-cli";
	}

	// Non-interactive: both flags provided
	if (opts.apiKey && opts.userId) {
		config.platform.apiKey = opts.apiKey;
		config.defaults.userId = opts.userId;
		await validatePlatform(config);
		saveConfig(config);
		printSuccess("Configuration saved to ~/.mem0/config.json");
		return;
	}

	printBanner();
	console.log();
	printInfo("Welcome! Let's set up your mem0 CLI.\n");

	// Use provided API key or prompt
	if (opts.apiKey) {
		config.platform.apiKey = opts.apiKey;
	} else {
		console.log(`  ${brand("How would you like to authenticate?")}`);
		console.log(`  ${dim("1.")} Login with email ${dim("(recommended)")}`);
		console.log(`  ${dim("2.")} Enter API key manually`);
		console.log();

		const choice = await promptLine(`  ${brand("Choose")} [1/2]`, "1");

		if (choice === "1") {
			console.log();
			const emailAddr = await promptLine(`  ${brand("Email")}`);
			if (!emailAddr) {
				printError("Email is required.");
				process.exit(1);
			}

			const email = emailAddr.trim().toLowerCase();
			validateEmail(email);
			printInfo(`Logging in as ${email}...\n`);

			const result = await emailLogin(email, undefined, baseUrl);

			const apiKeyVal = result.api_key as string | undefined;
			if (!apiKeyVal) {
				printError(
					"Auth succeeded but no API key was returned. Contact support.",
				);
				process.exit(1);
			}

			config.platform.apiKey = apiKeyVal;
			config.platform.baseUrl = baseUrl;
			config.platform.userEmail = email;
			config.defaults.userId =
				opts.userId || process.env.USER || process.env.USERNAME || "mem0-cli";

			saveConfig(config);
			console.log();
			printSuccess("Authenticated! Configuration saved to ~/.mem0/config.json");
			console.log();
			console.log(`  ${dim("Get started:")}`);
			console.log(`  ${dim('  mem0 add "I prefer dark mode"')}`);
			console.log(`  ${dim('  mem0 search "preferences"')}`);
			console.log();
			return;
		}

		// choice === "2": fall through to API key prompt
		await setupPlatform(config);
	}

	// Use provided user ID or prompt
	if (opts.userId) {
		config.defaults.userId = opts.userId;
	} else {
		await setupDefaults(config);
	}

	await validatePlatform(config);

	saveConfig(config);
	console.log();
	printSuccess("Configuration saved to ~/.mem0/config.json");
	console.log();
	console.log(`  ${dim("Get started:")}`);
	if (config.defaults.userId) {
		console.log(`  ${dim('  mem0 add "I prefer dark mode"')}`);
		console.log(`  ${dim('  mem0 search "preferences"')}`);
	} else {
		console.log(`  ${dim('  mem0 add "I prefer dark mode" --user-id alice')}`);
		console.log(`  ${dim('  mem0 search "preferences" --user-id alice')}`);
	}
	console.log();
}