import { n as logger } from "./logger-Dyl4VcLO.js";
import { i as readQueue, r as markTaskDone } from "./proactive-agent-B7u3Bj_l.js";
import https from "https";
//#region src/core/notification-dispatcher.ts
async function sendTelegram(token, chatId, text) {
	const body = JSON.stringify({
		chat_id: chatId,
		text,
		parse_mode: "Markdown"
	});
	await new Promise((resolve, reject) => {
		const req = https.request(`https://api.telegram.org/bot${token}/sendMessage`, {
			method: "POST",
			headers: {
				"Content-Type": "application/json",
				"Content-Length": Buffer.byteLength(body)
			}
		}, (res) => {
			res.resume();
			resolve();
		});
		req.on("error", reject);
		req.write(body);
		req.end();
	});
}
async function sendSlack(webhookUrl, text) {
	const body = JSON.stringify({ text });
	const url = new URL(webhookUrl);
	await new Promise((resolve, reject) => {
		const req = https.request({
			hostname: url.hostname,
			path: url.pathname + url.search,
			method: "POST",
			headers: {
				"Content-Type": "application/json",
				"Content-Length": Buffer.byteLength(body)
			}
		}, (res) => {
			res.resume();
			resolve();
		});
		req.on("error", reject);
		req.write(body);
		req.end();
	});
}
function formatTaskMessage(task) {
	const payload = task.payload;
	const slug = task.slug ?? "";
	switch (task.type) {
		case "daily_briefing": {
			const b = payload;
			const lines = ["📋 *Daily CRM Briefing*", ""];
			if (b.urgent?.length) {
				lines.push("🚨 *Urgent:*");
				b.urgent.slice(0, 3).forEach((u) => lines.push(`• ${u}`));
				lines.push("");
			}
			if (b.forecast) lines.push(`📊 ${b.forecast}`);
			if (b.topAction) lines.push(`\n⚡ *Top Action:* ${b.topAction}`);
			return lines.join("\n");
		}
		case "relationship_decay_alert": return `⚠️ *Relationship Alert: ${slug}*\n${String(payload["name"] ?? "")} — ${String(payload["daysSinceContact"] ?? "?")} days silent, grade ${String(payload["grade"] ?? "?")}`;
		case "deal_risk_alert": return `🔴 *Deal Risk: ${slug}*\n"${String(payload["dealName"] ?? "")}" closes in ${String(payload["daysToClose"] ?? "?")} days`;
		case "external_signal_alert": return `💡 *Signal: ${slug}*\n${String(payload["summary"] ?? "")}`;
		case "follow_up_nudge": return `📞 *Follow-up: ${slug}*\n${String(payload["message"] ?? "")}`;
		default: return `📌 CRM Task (${task.type})\n${JSON.stringify(payload).slice(0, 200)}`;
	}
}
async function drainProactiveQueue(dataDir) {
	const token = process.env["TELEGRAM_BOT_TOKEN"];
	const chatId = process.env["TELEGRAM_CHAT_ID"];
	const slackUrl = process.env["SLACK_WEBHOOK_URL"];
	const tasks = readQueue(dataDir).filter((t) => t.status === "pending");
	let sent = 0;
	let failed = 0;
	for (const task of tasks) {
		const message = formatTaskMessage(task);
		try {
			if (task.channel === "telegram" && token && chatId) await sendTelegram(token, chatId, message);
			else if (task.channel === "slack" && slackUrl) await sendSlack(slackUrl, message);
			await markTaskDone(dataDir, task.id, "dispatched");
			sent++;
		} catch (err) {
			failed++;
			logger.error("dispatch", "task failed", {
				task: task.id,
				error: err.message
			});
		}
	}
	return {
		sent,
		failed
	};
}
//#endregion
export { drainProactiveQueue };

//# sourceMappingURL=notification-dispatcher-inpKyuBz.js.map