import { a as readMainFacts } from "./customer-dir-CkMMXhb0.js";
import { t as writeFileAtomic } from "./atomic-write-8yjqqLtS.js";
import { t as withJsonFile } from "./file-lock-CcHotQkZ.js";
import path from "path";
import fs from "fs";
import matter from "gray-matter";
import { z } from "zod";
import yaml from "js-yaml";
//#region src/schemas/email-template.ts
const EmailTemplateSchema = z.object({
	id: z.string().min(1),
	subject: z.string().min(1),
	category: z.string().default("general"),
	variables: z.array(z.string()).default([]),
	language: z.string().default("de"),
	createdAt: z.string(),
	updatedAt: z.string().optional()
});
//#endregion
//#region src/fs/template-store.ts
function templatesDir(dataDir) {
	return path.join(dataDir, ".agentic", "templates");
}
function parseTemplateFile(filePath, id) {
	try {
		const raw = matter(fs.readFileSync(filePath, "utf-8"));
		const result = EmailTemplateSchema.safeParse({
			id,
			createdAt: (/* @__PURE__ */ new Date()).toISOString(),
			...raw.data
		});
		if (!result.success) return null;
		return {
			...result.data,
			body: raw.content.trim()
		};
	} catch {
		return null;
	}
}
function listTemplates(dataDir, opts) {
	const base = templatesDir(dataDir);
	if (!fs.existsSync(base)) return [];
	const results = [];
	const categories = fs.readdirSync(base).filter((name) => {
		try {
			return fs.statSync(path.join(base, name)).isDirectory();
		} catch {
			return false;
		}
	});
	for (const cat of categories) {
		if (opts?.category && cat !== opts.category) continue;
		const catDir = path.join(base, cat);
		const files = fs.readdirSync(catDir).filter((f) => f.endsWith(".md"));
		for (const file of files) {
			const id = file.replace(/\.md$/, "");
			const tmpl = parseTemplateFile(path.join(catDir, file), id);
			if (tmpl) results.push(tmpl);
		}
	}
	return results;
}
function getTemplate(dataDir, id) {
	const base = templatesDir(dataDir);
	if (!fs.existsSync(base)) return null;
	const categories = fs.existsSync(base) ? fs.readdirSync(base).filter((n) => {
		try {
			return fs.statSync(path.join(base, n)).isDirectory();
		} catch {
			return false;
		}
	}) : [];
	for (const cat of categories) {
		const p = path.join(base, cat, `${id}.md`);
		if (fs.existsSync(p)) return parseTemplateFile(p, id);
	}
	return null;
}
function writeTemplate(dataDir, tmpl) {
	const { body, ...meta } = tmpl;
	const category = meta.category ?? "general";
	const dir = path.join(templatesDir(dataDir), category);
	fs.mkdirSync(dir, { recursive: true });
	const content = matter.stringify(body, {
		...meta,
		updatedAt: (/* @__PURE__ */ new Date()).toISOString()
	});
	writeFileAtomic(path.join(dir, `${tmpl.id}.md`), content);
}
function deleteTemplate(dataDir, id) {
	const tmpl = getTemplate(dataDir, id);
	if (!tmpl) return false;
	const p = path.join(templatesDir(dataDir), tmpl.category, `${id}.md`);
	if (fs.existsSync(p)) {
		fs.unlinkSync(p);
		return true;
	}
	return false;
}
//#endregion
//#region src/core/template-engine.ts
const VARIABLE_REGEX = /\{\{([a-zA-Z_][a-zA-Z0-9_]*)\}\}/g;
function interpolate(template, vars) {
	return template.replace(VARIABLE_REGEX, (match, key) => {
		const val = vars[key];
		return val !== void 0 ? String(val) : match;
	});
}
function extractVariables(template) {
	return [...template.matchAll(new RegExp(VARIABLE_REGEX.source, "g"))].map((m) => m[1]);
}
async function buildVariablesFromCustomer(dataDir, slug) {
	const facts = await readMainFacts(dataDir, slug).catch(() => null);
	const now = /* @__PURE__ */ new Date();
	return {
		company: facts?.name ?? slug,
		domain: facts?.domain ?? "",
		email: facts?.email ?? "",
		stage: facts?.relationship_stage ?? "",
		slug,
		date: now.toLocaleDateString("de-DE"),
		year: now.getFullYear(),
		month: now.toLocaleDateString("de-DE", { month: "long" })
	};
}
//#endregion
//#region src/schemas/sequence.ts
const SequenceStepSchema = z.object({
	day: z.number().int().min(0),
	templateId: z.string().min(1),
	skipIfReplied: z.boolean().default(true)
});
const SequenceSchema = z.object({
	id: z.string().min(1),
	name: z.string().min(1),
	steps: z.array(SequenceStepSchema).min(1),
	createdAt: z.string()
});
const SequenceEnrollmentSchema = z.object({
	id: z.string(),
	sequenceId: z.string(),
	slug: z.string(),
	contactEmail: z.string().email(),
	enrolledAt: z.string(),
	status: z.enum([
		"active",
		"paused",
		"completed",
		"bounced"
	]),
	currentStep: z.number().int().min(0),
	stepsCompleted: z.array(z.number()),
	lastSentAt: z.string().optional(),
	lastRepliedAt: z.string().optional()
});
//#endregion
//#region src/fs/sequence-store.ts
function sequencesDir(dataDir) {
	return path.join(dataDir, ".agentic", "sequences");
}
function enrollmentsPath(dataDir) {
	return path.join(dataDir, ".agentic", "sequence-enrollments.json");
}
function listSequences(dataDir) {
	const dir = sequencesDir(dataDir);
	if (!fs.existsSync(dir)) return [];
	const files = fs.readdirSync(dir).filter((f) => f.endsWith(".yaml"));
	const results = [];
	for (const file of files) try {
		const content = fs.readFileSync(path.join(dir, file), "utf-8");
		const raw = yaml.load(content);
		const parsed = SequenceSchema.safeParse(raw);
		if (parsed.success) results.push(parsed.data);
	} catch {}
	return results;
}
function getSequence(dataDir, id) {
	return listSequences(dataDir).find((s) => s.id === id) ?? null;
}
function writeSequence(dataDir, seq) {
	const dir = sequencesDir(dataDir);
	fs.mkdirSync(dir, { recursive: true });
	const content = yaml.dump(seq);
	writeFileAtomic(path.join(dir, `${seq.id}.yaml`), content);
}
function readEnrollments(dataDir) {
	const p = enrollmentsPath(dataDir);
	if (!fs.existsSync(p)) return [];
	try {
		const raw = JSON.parse(fs.readFileSync(p, "utf-8"));
		return Array.isArray(raw) ? raw : [];
	} catch {
		return [];
	}
}
async function writeEnrollment(dataDir, enrollment) {
	await withJsonFile(enrollmentsPath(dataDir), (current) => {
		return [...Array.isArray(current) ? current : [], enrollment];
	});
}
async function updateEnrollment(dataDir, id, updates) {
	let updated = null;
	await withJsonFile(enrollmentsPath(dataDir), (current) => {
		const existing = Array.isArray(current) ? current : [];
		const idx = existing.findIndex((e) => e.id === id);
		if (idx < 0) return existing;
		const merged = SequenceEnrollmentSchema.parse({
			...existing[idx],
			...updates
		});
		updated = merged;
		const next = [...existing];
		next[idx] = merged;
		return next;
	});
	return updated;
}
//#endregion
export { writeEnrollment as a, extractVariables as c, getTemplate as d, listTemplates as f, updateEnrollment as i, interpolate as l, listSequences as n, writeSequence as o, writeTemplate as p, readEnrollments as r, buildVariablesFromCustomer as s, getSequence as t, deleteTemplate as u };

//# sourceMappingURL=sequence-store-CmYb6s0g.js.map