import { i as listCustomerSlugs } from "./customer-dir-CkMMXhb0.js";
import { t as withJsonFile } from "./file-lock-CcHotQkZ.js";
import { i as buildSimulationInput, l as runSimulation } from "./revenue-simulation-D8f_YkUY.js";
import { t as readPipeline } from "./pipeline-writer-CIllfnZl.js";
import { n as readHealth, t as computeCustomerHealth } from "./relationship-health-ZZNXR1RZ.js";
import path from "path";
import fs from "fs";
//#region src/core/proactive-agent.ts
function queuePath(dataDir) {
	return path.join(dataDir, ".agentic", "agent-queue.json");
}
function readQueue(dataDir) {
	const p = queuePath(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 enqueueTask(dataDir, task) {
	const now = (/* @__PURE__ */ new Date()).toISOString();
	const newTask = {
		...task,
		id: `task_${Date.now()}_${Math.random().toString(16).slice(2, 8)}`,
		createdAt: now,
		status: "pending"
	};
	await withJsonFile(queuePath(dataDir), (current) => {
		return [...Array.isArray(current) ? current : [], newTask];
	});
	return newTask;
}
async function markTaskDone(dataDir, taskId, result) {
	await withJsonFile(queuePath(dataDir), (current) => {
		const tasks = Array.isArray(current) ? [...current] : [];
		const idx = tasks.findIndex((t) => t.id === taskId);
		if (idx >= 0) tasks[idx] = {
			...tasks[idx],
			status: "done",
			...result ? { result } : {}
		};
		return tasks;
	});
}
async function buildDailyBriefing(dataDir, today) {
	const slugs = listCustomerSlugs(dataDir);
	const urgent = [];
	const opportunities = [];
	const todayDate = /* @__PURE__ */ new Date(`${today}T00:00:00Z`);
	const customerData = await Promise.all(slugs.map(async (slug) => {
		return {
			slug,
			health: readHealth(dataDir, slug) ?? computeCustomerHealth(dataDir, slug, today),
			deals: await readPipeline(dataDir, slug).catch(() => [])
		};
	}));
	for (const { slug, health, deals } of customerData) {
		for (const contact of health.contacts) if (contact.riskFlags.includes("NO_CONTACT_30D")) urgent.push(`${slug}: ${contact.name} has been silent for ${contact.daysSinceContact} days — health ${contact.score}/100`);
		const activeDeals = deals.filter((d) => d.stage !== "won" && d.stage !== "lost");
		if (health.overallHealth >= 65 && activeDeals.length > 0) opportunities.push(`${slug}: relationship health ${health.overallHealth}/100 with ${activeDeals.length} active deal(s) — good time for expansion or upsell.`);
		for (const deal of deals) {
			if (deal.stage === "won" || deal.stage === "lost") continue;
			if (deal.close_date && deal.close_date.trim() !== "") {
				const daysToClose = Math.floor((new Date(deal.close_date).getTime() - todayDate.getTime()) / 864e5);
				if (daysToClose <= 7 && daysToClose >= 0) urgent.push(`${slug}: Deal "${deal.name}" closes in ${daysToClose} day(s) — ${deal.stage}`);
				else if (daysToClose < 0) urgent.push(`${slug}: Deal "${deal.name}" close date passed (${Math.abs(daysToClose)} days overdue)`);
			}
		}
	}
	let forecast = "No active pipeline.";
	try {
		const simInput = await buildSimulationInput(dataDir, "quarter", today);
		if (simInput.deals.length > 0) {
			const sim = runSimulation({
				...simInput,
				iterations: 1e3
			});
			forecast = `Q forecast: P50 €${(sim.p50 / 1e3).toFixed(1)}k / P90 €${(sim.p90 / 1e3).toFixed(1)}k — ${simInput.deals.length} deal(s) in pipeline.`;
		}
	} catch {}
	const topAction = urgent.length > 0 ? urgent[0].replace(/^[^:]+: /, "").split("—")[0]?.trim() ?? urgent[0] : "Review your pipeline and schedule next customer check-ins.";
	return {
		date: today,
		generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
		urgent,
		opportunities,
		forecast,
		topAction
	};
}
//#endregion
export { readQueue as i, enqueueTask as n, markTaskDone as r, buildDailyBriefing as t };

//# sourceMappingURL=proactive-agent-B7u3Bj_l.js.map