import { i as readInteractions, n as appendInteraction } from "./interactions-writer-B8XAzdqR.js";
import { n as indexInLanceDB } from "./lancedb-CuHKNsNZ.js";
import path from "path";
import fs from "fs";
//#region src/sync/google-drive-sync.ts
const GOOGLE_DOC_MIME = "application/vnd.google-apps.document";
const DRIVE_API_BASE = "https://www.googleapis.com/drive/v3";
async function syncGoogleDriveFiles(opts) {
	const { slug, dataDir, accessToken } = opts;
	const searchName = opts.customerName ?? slug;
	const maxFiles = opts.maxFiles ?? 200;
	const result = {
		synced: 0,
		skipped: 0,
		errors: []
	};
	let existingInteractions = "";
	try {
		existingInteractions = await readInteractions(dataDir, slug);
	} catch {
		existingInteractions = "";
	}
	const encodedQuery = encodeURIComponent(`name contains "${searchName}" and mimeType!="application/vnd.google-apps.folder"`);
	const fields = encodeURIComponent("files(id,name,mimeType,webViewLink,modifiedTime,size),nextPageToken");
	let pageToken;
	let totalFetched = 0;
	do {
		let url = `${DRIVE_API_BASE}/files?q=${encodedQuery}&fields=${fields}&pageSize=50`;
		if (pageToken) url += `&pageToken=${encodeURIComponent(pageToken)}`;
		let response;
		try {
			response = await fetch(url, { headers: { Authorization: `Bearer ${accessToken}` } });
		} catch (err) {
			result.errors.push(`Drive API request failed: ${err.message}`);
			break;
		}
		if (!response.ok) {
			result.errors.push(`Drive API error ${response.status}: ${await response.text().catch(() => "unknown")}`);
			break;
		}
		let data;
		try {
			data = await response.json();
		} catch (err) {
			result.errors.push(`Failed to parse Drive API response: ${err.message}`);
			break;
		}
		const files = data.files ?? [];
		pageToken = data.nextPageToken;
		for (const file of files) {
			if (totalFetched >= maxFiles) break;
			totalFetched++;
			const sourceRef = `google://drive/${file.id}`;
			if (existingInteractions.includes(sourceRef)) {
				result.skipped++;
				continue;
			}
			try {
				if (file.mimeType === GOOGLE_DOC_MIME) {
					const exportUrl = `${DRIVE_API_BASE}/files/${file.id}/export?mimeType=${encodeURIComponent("text/plain")}`;
					const exportRes = await fetch(exportUrl, { headers: { Authorization: `Bearer ${accessToken}` } });
					if (!exportRes.ok) {
						result.errors.push(`Failed to export doc '${file.name}': HTTP ${exportRes.status}`);
						continue;
					}
					const text = await exportRes.text();
					const attachmentsDir = path.join(dataDir, "customers", slug, "attachments");
					fs.mkdirSync(attachmentsDir, { recursive: true });
					const safeFilename = file.name.replace(/[/\\?%*:|"<>]/g, "-") + ".txt";
					fs.writeFileSync(path.join(attachmentsDir, safeFilename), text, "utf-8");
					await appendInteraction(dataDir, slug, {
						date: file.modifiedTime ? file.modifiedTime.slice(0, 10) : (/* @__PURE__ */ new Date()).toISOString().slice(0, 10),
						type: "Note",
						with: "Google Drive",
						summary: `Attachment: ${file.name}`,
						nextSteps: [],
						sourceRef,
						synced: (/* @__PURE__ */ new Date()).toISOString()
					});
					const lanceOpts = { type: "attachment" };
					if (file.modifiedTime) lanceOpts.date = file.modifiedTime.slice(0, 10);
					await indexInLanceDB(dataDir, slug, text.slice(0, 2e3), sourceRef, lanceOpts);
				} else await appendInteraction(dataDir, slug, {
					date: file.modifiedTime ? file.modifiedTime.slice(0, 10) : (/* @__PURE__ */ new Date()).toISOString().slice(0, 10),
					type: "Note",
					with: "Google Drive",
					summary: `Attachment: ${file.name}${file.webViewLink ? ` — ${file.webViewLink}` : ""}`,
					nextSteps: [],
					sourceRef,
					synced: (/* @__PURE__ */ new Date()).toISOString()
				});
				result.synced++;
				existingInteractions += sourceRef;
			} catch (err) {
				result.errors.push(`Error processing '${file.name}': ${err.message}`);
			}
		}
		if (totalFetched >= maxFiles) break;
	} while (pageToken);
	return result;
}
//#endregion
export { syncGoogleDriveFiles };

//# sourceMappingURL=google-drive-sync-B_I1d54Y.js.map