import { n as logger } from "./logger-Dyl4VcLO.js";
import { d as getTemplate, i as updateEnrollment, l as interpolate, r as readEnrollments, s as buildVariablesFromCustomer, t as getSequence } from "./sequence-store-CmYb6s0g.js";
import path from "path";
import fs from "fs";
//#region src/core/sequence-engine.ts
/**
* Add n days to an ISO date string (YYYY-MM-DD) and return YYYY-MM-DD.
*/
function addDays(isoDateStr, n) {
	const [year, month, day] = isoDateStr.split("-").map(Number);
	const date = new Date(Date.UTC(year, month - 1, day));
	date.setUTCDate(date.getUTCDate() + n);
	return date.toISOString().slice(0, 10);
}
async function processSequenceStep(dataDir, enrollment, today) {
	const sequence = getSequence(dataDir, enrollment.sequenceId);
	if (!sequence) {
		logger.warn("sequences", "sequence not found", { sequenceId: enrollment.sequenceId });
		return "no_step_due";
	}
	if (enrollment.currentStep >= sequence.steps.length) {
		await updateEnrollment(dataDir, enrollment.id, { status: "completed" });
		return "completed";
	}
	const step = sequence.steps[enrollment.currentStep];
	if (today < addDays(enrollment.enrolledAt.slice(0, 10), step.day)) return "no_step_due";
	if (step.skipIfReplied && enrollment.lastRepliedAt) {
		await updateEnrollment(dataDir, enrollment.id, { currentStep: enrollment.currentStep + 1 });
		return "skipped_replied";
	}
	const template = getTemplate(dataDir, step.templateId);
	if (!template) {
		logger.warn("sequences", "template not found, skipping step", { templateId: step.templateId });
		await updateEnrollment(dataDir, enrollment.id, {
			currentStep: enrollment.currentStep + 1,
			lastSentAt: (/* @__PURE__ */ new Date()).toISOString()
		});
		return "no_step_due";
	}
	const vars = await buildVariablesFromCustomer(dataDir, enrollment.slug);
	vars["contactEmail"] = enrollment.contactEmail;
	const subject = interpolate(template.subject, vars);
	const body = interpolate(template.body, vars);
	const tokenPath = path.join(dataDir, ".agentic", "gmail-token.json");
	const credPath = path.join(dataDir, ".agentic", "gmail-credentials.json");
	if (fs.existsSync(tokenPath) && fs.existsSync(credPath)) try {
		const { getGmailAuth } = await import("./gmail-auth-OComS92L.js");
		const { sendEmail } = await import("./gmail-sender-StTpJ9Ub.js");
		await sendEmail({
			auth: await getGmailAuth(credPath, tokenPath),
			to: enrollment.contactEmail,
			subject,
			body,
			isHtml: false
		});
		logger.info("sequences", "sent step", {
			step: enrollment.currentStep,
			to: enrollment.contactEmail
		});
	} catch (err) {
		logger.error("sequences", "send failed", { error: err.message });
	}
	else logger.warn("sequences", "gmail not configured, advancing step", { to: enrollment.contactEmail });
	await updateEnrollment(dataDir, enrollment.id, {
		currentStep: enrollment.currentStep + 1,
		lastSentAt: (/* @__PURE__ */ new Date()).toISOString(),
		stepsCompleted: [...enrollment.stepsCompleted, enrollment.currentStep]
	});
	return "sent";
}
async function runSequenceCycle(dataDir, today) {
	const active = readEnrollments(dataDir).filter((e) => e.status === "active");
	let sent = 0;
	let completed = 0;
	const errors = [];
	for (const enrollment of active) try {
		const result = await processSequenceStep(dataDir, enrollment, today);
		if (result === "sent") sent++;
		if (result === "completed") completed++;
	} catch (err) {
		const msg = `${enrollment.id}: ${err.message}`;
		errors.push(msg);
		logger.error("sequences", "error processing enrollment", {
			enrollment: enrollment.id,
			error: err.message
		});
	}
	return {
		processed: active.length,
		sent,
		completed,
		errors
	};
}
//#endregion
export { processSequenceStep as n, runSequenceCycle as r, addDays as t };

//# sourceMappingURL=sequence-engine-DNTVLq7o.js.map