const require_chunk = require("./chunk-DakpK96I.cjs");
const require_session_store = require("./session-store-yfwnj0OC.cjs");
const require_interactions_writer = require("./interactions-writer-BRJNrefF.cjs");
const require_logger = require("./logger-BkInaGoV.cjs");
const require_llm = require("./llm-CXycmEl9.cjs");
let path = require("path");
path = require_chunk.__toESM(path, 1);
let fs = require("fs");
fs = require_chunk.__toESM(fs, 1);
let zod = require("zod");
let _googleapis_gmail = require("@googleapis/gmail");
let https = require("https");
https = require_chunk.__toESM(https, 1);
//#region src/schemas/agent-config.ts
const AgentConfigSchema = zod.z.object({
	slug: zod.z.string().min(1),
	channel: zod.z.enum(["telegram"]),
	wakeOn: zod.z.array(zod.z.enum(["email", "calendar"])).default(["email"]),
	createdAt: zod.z.string(),
	lastWake: zod.z.string().nullable().default(null),
	telegramChatId: zod.z.string().optional()
});
//#endregion
//#region src/core/agent-notifier.ts
function agentConfigPath(dataDir, slug) {
	return path.default.join(dataDir, ".agentic", "agents", `${slug}.agent.json`);
}
function readAgentConfig(dataDir, slug) {
	const p = agentConfigPath(dataDir, slug);
	if (!fs.default.existsSync(p)) return null;
	try {
		const raw = JSON.parse(fs.default.readFileSync(p, "utf-8"));
		const result = AgentConfigSchema.safeParse(raw);
		return result.success ? result.data : null;
	} catch {
		return null;
	}
}
function writeLastWake(dataDir, slug, config) {
	const p = agentConfigPath(dataDir, slug);
	try {
		require_session_store.writeJsonFile(p, {
			...config,
			lastWake: (/* @__PURE__ */ new Date()).toISOString()
		});
	} catch {}
}
function sendTelegramMessage(token, chatId, text) {
	const body = JSON.stringify({
		chat_id: chatId,
		text,
		parse_mode: "Markdown"
	});
	return new Promise((resolve, reject) => {
		const req = https.default.request(`https://api.telegram.org/bot${token}/sendMessage`, {
			method: "POST",
			headers: {
				"Content-Type": "application/json",
				"Content-Length": Buffer.byteLength(body)
			}
		}, (res) => {
			res.resume();
			resolve();
		});
		req.on("error", reject);
		req.write(body);
		req.end();
	});
}
function buildWakeMessage(slug, subject, summary, nextSteps) {
	return `📧 New email from **${slug}**: ${subject}\n${summary}\n\n💡 Suggested action: ${nextSteps[0] ?? "Follow up within 24h"}`;
}
/**
* Fire-and-forget notification: reads the agent config for `slug`, summarises
* the inbound email with the LLM, and sends a Telegram message.
*
* Silently returns (no throw) when:
* - no agent config exists for the slug
* - TELEGRAM_BOT_TOKEN env var is not set
* - no chat id is available (neither in config nor in TELEGRAM_CHAT_ID env var)
* - any HTTPS / LLM error occurs
*/
async function notifyAgentWake(dataDir, slug, context) {
	try {
		const config = readAgentConfig(dataDir, slug);
		if (!config) return;
		const token = process.env["TELEGRAM_BOT_TOKEN"];
		if (!token) return;
		const chatId = config.telegramChatId ?? process.env["TELEGRAM_CHAT_ID"];
		if (!chatId) return;
		const emailSummary = await require_llm.summarizeEmail(context.subject, context.snippet, context.from);
		await sendTelegramMessage(token, chatId, buildWakeMessage(slug, context.subject, emailSummary.summary, emailSummary.nextSteps));
		writeLastWake(dataDir, slug, config);
	} catch {}
}
//#endregion
//#region src/sync/gmail-sync.ts
/**
* Retry a function with exponential backoff on any error.
* Delays: 1s, 2s, 4s, 8s … (2^attempt seconds), up to maxRetries retries.
*/
async function retryWithBackoff(fn, maxRetries = 3) {
	let attempt = 0;
	while (true) try {
		return await fn();
	} catch (err) {
		if (attempt >= maxRetries) throw err;
		await sleep(1e3 * Math.pow(2, attempt));
		attempt++;
	}
}
async function syncGmail(opts) {
	const gmail = (0, _googleapis_gmail.gmail)({
		version: "v1",
		auth: opts.auth
	});
	const maxPages = opts.maxPages ?? 5;
	const includeAttachments = opts.includeAttachments ?? true;
	let q = opts.query;
	if (opts.since) {
		const after = Math.floor(opts.since.getTime() / 1e3);
		q += ` after:${after}`;
	}
	const allMessages = [];
	let pageToken = void 0;
	let pagesFetched = 0;
	do {
		const listResp = await gmail.users.messages.list({
			userId: "me",
			q,
			maxResults: 200,
			...pageToken ? { pageToken } : {}
		});
		const pageMessages = listResp.data.messages ?? [];
		allMessages.push(...pageMessages);
		pageToken = listResp.data.nextPageToken ?? void 0;
		pagesFetched++;
	} while (pageToken && pagesFetched < maxPages);
	let existingContent = await require_interactions_writer.readInteractions(opts.dataDir, opts.slug);
	let synced = 0;
	let skipped = 0;
	for (const msg of allMessages) {
		if (!msg.id) continue;
		const source = `gmail://thread/${msg.threadId ?? msg.id}`;
		if (existingContent.includes(source)) {
			skipped++;
			continue;
		}
		await sleep(100);
		let msgData;
		try {
			msgData = (await retryWithBackoff(() => gmail.users.messages.get({
				userId: "me",
				id: msg.id,
				...includeAttachments ? { format: "full" } : {
					format: "metadata",
					metadataHeaders: [
						"Subject",
						"From",
						"Date"
					]
				}
			}))).data;
		} catch (err) {
			require_logger.logger.warn("gmail-sync", "skipping message after retries", {
				messageId: msg.id,
				error: err.message
			});
			skipped++;
			continue;
		}
		const headers = msgData.payload?.headers ?? [];
		const subject = headers.find((h) => h.name === "Subject")?.value ?? "(no subject)";
		const from = headers.find((h) => h.name === "From")?.value ?? "";
		const dateStr = headers.find((h) => h.name === "Date")?.value;
		const date = dateStr ? new Date(dateStr).toISOString().slice(0, 10) : (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
		const snippet = msgData.snippet ?? "";
		const { extractEmailBodyMarkdown } = await Promise.resolve().then(() => require("./email-body-BFSRa0AW.cjs"));
		const body = await extractEmailBodyMarkdown(msgData.payload ?? void 0) || snippet;
		const { summarizeEmail } = await Promise.resolve().then(() => require("./llm-CXycmEl9.cjs")).then((n) => n.llm_exports);
		const emailSummary = await summarizeEmail(subject, body, from);
		let attachmentLinks = [];
		if (includeAttachments) try {
			const { processMessageAttachments } = await Promise.resolve().then(() => require("./attachments-Dbe7Bidz.cjs"));
			attachmentLinks = (await processMessageAttachments({
				gmail,
				dataDir: opts.dataDir,
				slug: opts.slug,
				messageId: msg.id,
				source,
				payload: msgData.payload ?? void 0,
				date,
				...opts.maxAttachmentBytes !== void 0 ? { maxBytes: opts.maxAttachmentBytes } : {}
			})).map((a) => a.markdownName);
		} catch (err) {
			require_logger.logger.warn("gmail-sync", "attachment processing failed", {
				messageId: msg.id,
				error: err.message
			});
		}
		await require_interactions_writer.appendInteraction(opts.dataDir, opts.slug, {
			date,
			type: "Email",
			direction: detectDirection(from),
			with: from,
			subject,
			summary: emailSummary.summary,
			nextSteps: emailSummary.nextSteps,
			...attachmentLinks.length > 0 ? { attachments: attachmentLinks } : {},
			sourceRef: source,
			synced: (/* @__PURE__ */ new Date()).toISOString()
		});
		existingContent += source;
		const { indexInLanceDB } = await Promise.resolve().then(() => require("./mcp.cjs")).then((n) => n.lancedb_exports);
		const { chunkText } = await Promise.resolve().then(() => require("./chunk-BfDYWZQ8.cjs"));
		const bodyChunks = chunkText(`${subject}\n${body}`);
		for (let i = 0; i < bodyChunks.length; i++) {
			const ref = i === 0 ? source : `${source}#${i}`;
			await indexInLanceDB(opts.dataDir, opts.slug, bodyChunks[i], ref, {
				date,
				type: "Email"
			}).catch((err) => {
				require_logger.logger.error("gmail-sync", "LanceDB index failed", { error: err.message });
			});
		}
		if (agentConfigExists(opts.dataDir, opts.slug)) notifyAgentWake(opts.dataDir, opts.slug, {
			trigger: "email",
			subject,
			from,
			snippet
		}).catch(() => {});
		synced++;
	}
	return {
		synced,
		skipped
	};
}
function agentConfigExists(dataDir, slug) {
	const configPath = path.default.join(dataDir, ".agentic", "agents", `${slug}.agent.json`);
	return fs.default.existsSync(configPath);
}
function detectDirection(_from) {
	return "inbound";
}
function sleep(ms) {
	return new Promise((resolve) => setTimeout(resolve, ms));
}
//#endregion
exports.syncGmail = syncGmail;

//# sourceMappingURL=gmail-sync-CodrUNR4.cjs.map