import { a as readMainFacts, n as customerExists } from "./customer-dir-CkMMXhb0.js";
import { i as success, n as error, r as info } from "./colors-BG07TZQz.js";
import { n as getSession, r as setSession, t as clearSession } from "./session-store-CEa39Dxs.js";
import { Command } from "commander";
import path from "path";
import fs from "fs";
//#region src/commands/session.ts
function sessionsDir(dataDir) {
	return path.join(dataDir, ".agentic", "sessions");
}
function persistSession(dataDir, session) {
	const dir = sessionsDir(dataDir);
	fs.mkdirSync(dir, { recursive: true });
	const key = (session.owner ?? `pid-${process.pid}`).replace(/[^a-zA-Z0-9_-]/g, "_");
	fs.writeFileSync(path.join(dir, `${key}.json`), JSON.stringify({
		...session,
		pid: process.pid
	}));
}
function clearPersistedSession(dataDir, owner) {
	const dir = sessionsDir(dataDir);
	if (!fs.existsSync(dir)) return;
	if (owner !== void 0) {
		const key = owner.replace(/[^a-zA-Z0-9_-]/g, "_");
		const file = path.join(dir, `${key}.json`);
		if (fs.existsSync(file)) fs.unlinkSync(file);
		return;
	}
	try {
		for (const f of fs.readdirSync(dir).filter((n) => n.endsWith(".json"))) try {
			fs.unlinkSync(path.join(dir, f));
		} catch {}
	} catch {}
}
function readAllSessions(dataDir) {
	const dir = sessionsDir(dataDir);
	if (!fs.existsSync(dir)) return [];
	return fs.readdirSync(dir).filter((f) => f.endsWith(".json")).map((f) => {
		try {
			return JSON.parse(fs.readFileSync(path.join(dir, f), "utf-8"));
		} catch {
			return null;
		}
	}).filter((s) => s !== null);
}
const sessionCommand = new Command("session").description("Manage the active customer session");
sessionCommand.command("open <slug>").option("--owner <owner>", "Set the owner of this session").action(async (slug, opts) => {
	const dataDir = process.env["DXCRM_DATA_DIR"] ?? process.cwd();
	if (!customerExists(dataDir, slug)) {
		console.error(error(`✗ Customer not found: ${slug}`));
		process.exit(1);
	}
	const facts = await readMainFacts(dataDir, slug);
	const owner = opts.owner ?? process.env["DXCRM_ACTOR"];
	const session = {
		customerSlug: slug,
		customerName: facts.name,
		startedAt: (/* @__PURE__ */ new Date()).toISOString(),
		...owner !== void 0 ? { owner } : {}
	};
	setSession(session);
	persistSession(dataDir, session);
	console.log(success(`✓ Session opened: ${facts.name}`));
});
sessionCommand.command("close").action(() => {
	const dataDir = process.env["DXCRM_DATA_DIR"] ?? process.cwd();
	const s = getSession() ?? readAllSessions(dataDir)[0] ?? null;
	clearSession();
	clearPersistedSession(dataDir, s?.owner);
	console.log(success("✓ Session closed."));
});
sessionCommand.command("status").action(() => {
	const dataDir = process.env["DXCRM_DATA_DIR"] ?? process.cwd();
	const s = getSession() ?? readAllSessions(dataDir)[0] ?? null;
	if (!s) console.log(info("No active session."));
	else console.log(info(`Active: ${s.customerName} (${s.customerSlug}) since ${s.startedAt}`));
});
//#endregion
export { sessionCommand as i, persistSession as n, readAllSessions as r, clearPersistedSession as t };

//# sourceMappingURL=session-BgGDyP2C.js.map