import { t as writeFileAtomic } from "./atomic-write-8yjqqLtS.js";
import path from "path";
import fs from "fs";
import { z } from "zod";
import { createHmac } from "crypto";
import yaml from "js-yaml";
//#region src/schemas/survey.ts
const SurveyDefinitionSchema = z.object({
	id: z.string().min(1),
	type: z.enum([
		"nps",
		"csat",
		"ces"
	]).default("nps"),
	question: z.string().min(1),
	scale: z.object({
		min: z.number().default(0),
		max: z.number().default(10)
	}).default({
		min: 0,
		max: 10
	}),
	includeComment: z.boolean().default(true),
	commentPrompt: z.string().optional(),
	createdAt: z.string()
});
const SurveyResponseSchema = z.object({
	surveyId: z.string(),
	slug: z.string(),
	contactEmail: z.string().email(),
	score: z.number().int(),
	comment: z.string().optional(),
	respondedAt: z.string(),
	token: z.string(),
	sentAt: z.string()
});
//#endregion
//#region src/core/survey-engine.ts
const SURVEY_SECRET = process.env["DXCRM_SURVEY_SECRET"] ?? "dxcrm-survey-default-secret";
function surveysDir(dataDir) {
	return path.join(dataDir, ".agentic", "surveys");
}
function responsesDir(dataDir, surveyId) {
	return path.join(dataDir, ".agentic", "survey-responses", surveyId);
}
function getSurvey(dataDir, surveyId) {
	const p = path.join(surveysDir(dataDir), `${surveyId}.yaml`);
	if (!fs.existsSync(p)) return null;
	try {
		const raw = yaml.load(fs.readFileSync(p, "utf-8"));
		const result = SurveyDefinitionSchema.safeParse(raw);
		return result.success ? result.data : null;
	} catch {
		return null;
	}
}
function writeSurvey(dataDir, survey) {
	const dir = surveysDir(dataDir);
	fs.mkdirSync(dir, { recursive: true });
	writeFileAtomic(path.join(dir, `${survey.id}.yaml`), yaml.dump(survey));
}
function listSurveys(dataDir) {
	const dir = surveysDir(dataDir);
	if (!fs.existsSync(dir)) return [];
	return fs.readdirSync(dir).filter((f) => f.endsWith(".yaml")).flatMap((f) => {
		const s = getSurvey(dataDir, f.replace(/\.yaml$/, ""));
		return s ? [s] : [];
	});
}
function generateSurveyToken(slug, contactEmail, surveyId) {
	return createHmac("sha256", SURVEY_SECRET).update(`${slug}:${contactEmail}:${surveyId}`).digest("hex").slice(0, 16);
}
function buildSurveyEmail(survey, serverUrl, token) {
	const buttons = Array.from({ length: survey.scale.max - survey.scale.min + 1 }, (_, i) => i + survey.scale.min).map((s) => `<a href="${serverUrl}/survey/respond?token=${token}&score=${s}" style="display:inline-block;margin:4px;padding:10px 16px;background:#1a1a2e;color:white;text-decoration:none;border-radius:4px;">${s}</a>`).join("");
	const body = `<p>${survey.question}</p>
<p>${buttons}</p>
${survey.includeComment ? `<p>Or <a href="${serverUrl}/survey/respond?token=${token}&comment=true">Click here to add a comment</a></p>` : ""}`;
	return {
		subject: survey.type === "nps" ? "How likely are you to recommend us?" : "Rate your experience",
		body
	};
}
async function recordSurveyResponse(dataDir, token, score, comment) {
	const pendingDir = path.join(dataDir, ".agentic", "survey-pending");
	if (!fs.existsSync(pendingDir)) return null;
	const files = fs.readdirSync(pendingDir).filter((f) => f.endsWith(".json"));
	for (const file of files) try {
		const pending = JSON.parse(fs.readFileSync(path.join(pendingDir, file), "utf-8"));
		if (pending.token !== token) continue;
		const response = {
			surveyId: pending.surveyId,
			slug: pending.slug,
			contactEmail: pending.contactEmail,
			score,
			...comment ? { comment } : {},
			respondedAt: (/* @__PURE__ */ new Date()).toISOString(),
			token,
			sentAt: pending.sentAt
		};
		const dir = responsesDir(dataDir, pending.surveyId);
		fs.mkdirSync(dir, { recursive: true });
		const filename = `${pending.slug}_${pending.contactEmail.replace("@", "_at_")}_${Date.now()}.json`;
		writeFileAtomic(path.join(dir, filename), JSON.stringify(response, null, 2));
		fs.unlinkSync(path.join(pendingDir, file));
		return response;
	} catch {
		continue;
	}
	return null;
}
function loadSurveyResponses(dataDir, surveyId, slug) {
	const dir = responsesDir(dataDir, surveyId);
	if (!fs.existsSync(dir)) return [];
	return fs.readdirSync(dir).filter((f) => f.endsWith(".json")).flatMap((f) => {
		try {
			const raw = JSON.parse(fs.readFileSync(path.join(dir, f), "utf-8"));
			const parsed = SurveyResponseSchema.safeParse(raw);
			if (!parsed.success) return [];
			if (slug && parsed.data.slug !== slug) return [];
			return [parsed.data];
		} catch {
			return [];
		}
	});
}
function calcNpsScore(responses) {
	if (responses.length === 0) return 0;
	const promoters = responses.filter((r) => r.score >= 9).length;
	const detractors = responses.filter((r) => r.score <= 6).length;
	return Math.round((promoters - detractors) / responses.length * 100);
}
async function savePendingSurvey(dataDir, surveyId, slug, contactEmail, token) {
	const pendingDir = path.join(dataDir, ".agentic", "survey-pending");
	fs.mkdirSync(pendingDir, { recursive: true });
	const filename = `${token}.json`;
	const pending = {
		token,
		surveyId,
		slug,
		contactEmail,
		sentAt: (/* @__PURE__ */ new Date()).toISOString()
	};
	writeFileAtomic(path.join(pendingDir, filename), JSON.stringify(pending, null, 2));
}
//#endregion
export { listSurveys as a, responsesDir as c, writeSurvey as d, getSurvey as i, savePendingSurvey as l, calcNpsScore as n, loadSurveyResponses as o, generateSurveyToken as r, recordSurveyResponse as s, buildSurveyEmail as t, surveysDir as u };

//# sourceMappingURL=survey-engine-DngXBv47.js.map