import { r as updateSlugSyncState } from "./sync-state-DMZgzpez.js";
import { n as appendInteraction } from "./interactions-writer-B8XAzdqR.js";
//#region src/sync/microsoft-sync.ts
async function syncMicrosoft(opts) {
	const result = {
		synced: 0,
		skipped: 0,
		errors: []
	};
	const maxResults = opts.maxResults ?? 50;
	let filter = "";
	if (opts.since) filter = `&$filter=receivedDateTime ge ${opts.since.toISOString()}`;
	if (opts.query) filter += (filter ? " and " : "&$filter=") + opts.query;
	const url = `https://graph.microsoft.com/v1.0/me/messages?$top=${maxResults}${filter}`;
	let messages;
	try {
		const res = await fetch(url, { headers: { Authorization: `Bearer ${opts.accessToken}` } });
		if (!res.ok) {
			result.errors.push(`Graph API error: ${res.status} ${res.statusText}`);
			return result;
		}
		messages = (await res.json()).value ?? [];
	} catch (err) {
		result.errors.push(`Network error: ${err.message}`);
		return result;
	}
	const { readInteractions } = await import("./interactions-writer-B2y-73lh.js");
	const existing = await readInteractions(opts.dataDir, opts.slug).catch(() => "");
	for (const msg of messages) {
		const sourceRef = `microsoft://message/${msg.id}`;
		if (existing.includes(sourceRef)) {
			result.skipped++;
			continue;
		}
		const date = msg.receivedDateTime ? new Date(msg.receivedDateTime).toISOString().slice(0, 10) : (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
		const from = msg.from?.emailAddress?.name ?? msg.from?.emailAddress?.address ?? "unknown";
		const subject = msg.subject ?? "(no subject)";
		const preview = msg.bodyPreview ?? "";
		let summary = preview.slice(0, 300);
		let nextSteps = [];
		try {
			const { summarizeEmail } = await import("./llm-DSX1-wFu.js");
			const llmResult = await summarizeEmail(subject, preview, from);
			summary = llmResult.summary;
			nextSteps = llmResult.nextSteps;
		} catch {}
		try {
			await appendInteraction(opts.dataDir, opts.slug, {
				date,
				type: "Email",
				with: from,
				summary: `${subject}: ${summary}`,
				nextSteps,
				sourceRef,
				synced: (/* @__PURE__ */ new Date()).toISOString()
			});
			result.synced++;
		} catch (err) {
			result.errors.push(`Failed to append ${msg.id}: ${err.message}`);
		}
	}
	if (result.synced > 0) updateSlugSyncState(opts.dataDir, opts.slug, { lastGmailSync: (/* @__PURE__ */ new Date()).toISOString() });
	return result;
}
//#endregion
export { syncMicrosoft };

//# sourceMappingURL=microsoft-sync-D30_XksI.js.map