import { A as writeMainFacts, D as ensureCustomerDir, E as customerExists, N as MainFactsSchema, O as listCustomerSlugs, _ as error, b as warning, c as getRole, d as readAuditLog, g as bold, h as runBackup, i as canSeeCustomer, k as readMainFacts, l as filterAuditLog, n as getSession, r as setSession, s as getRbacConfig, t as clearSession, v as info, w as writeJsonFile, y as success } from "./session-store-DWxJ5Pof.js";
import { t as writeFileAtomic } from "./atomic-write-8yjqqLtS.js";
import { Command } from "commander";
import path from "path";
import fs from "fs";
import slugify from "slug";
import matter from "gray-matter";
//#region src/commands/create.ts
async function createCustomer(opts) {
	const id = slugify(opts.name, { lower: true });
	const dataDir = opts.dataDir ?? process.env["DXCRM_DATA_DIR"] ?? process.cwd();
	await ensureCustomerDir(dataDir, id);
	const dir = path.join(dataDir, "customers", id);
	const today = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
	await writeMainFacts(dataDir, id, {
		name: opts.name,
		domain: opts.domain,
		email: opts.email,
		relationship_stage: "prospect",
		tags: [],
		currency: "EUR",
		created: today,
		updated: today
	});
	const interactionsPath = path.join(dir, "interactions.md");
	if (!fs.existsSync(interactionsPath)) writeFileAtomic(interactionsPath, `# Interactions — ${opts.name}\n\n`);
	const pipelinePath = path.join(dir, "pipeline.md");
	if (!fs.existsSync(pipelinePath)) writeFileAtomic(pipelinePath, `# Pipeline — ${opts.name}\n\n| Deal | Stage | Value | Currency | Probability | Close Date | Updated | Notes |\n|---|---|---|---|---|---|---|---|\n`);
	const sourcesPath = path.join(dir, "sources.json");
	if (!fs.existsSync(sourcesPath)) writeJsonFile(sourcesPath, {
		gmail: {
			type: "gmail",
			query: opts.domain ? `from:${opts.domain} OR to:${opts.domain}` : opts.email ? `from:${opts.email} OR to:${opts.email}` : "",
			enabled: true
		},
		version: 1,
		created: (/* @__PURE__ */ new Date()).toISOString()
	});
	return {
		id,
		dir
	};
}
new Command("create").description("Create a new customer").argument("<name>", "Customer name").option("--domain <domain>", "Primary domain (for Gmail sync)").option("--email <email>", "Primary contact email").action(async (name, opts) => {
	try {
		const { id, dir } = await createCustomer({
			name,
			...opts
		});
		console.log(success(`✓ Created customer: ${bold(id)}`));
		console.log(`  Dir: ${dir}`);
		console.log(`  Files: main_facts.md, interactions.md, pipeline.md, sources.json`);
	} catch (err) {
		console.error(error(`✗ ${err.message}`));
		process.exit(1);
	}
});
//#endregion
//#region src/commands/audit.ts
const SEP = "─".repeat(70);
async function runAudit(opts, dataDir) {
	const dir = dataDir ?? process.cwd();
	const limit = opts.limit ?? 20;
	const entries = filterAuditLog(readAuditLog(dir), {
		...opts.slug !== void 0 ? { slug: opts.slug } : {},
		...opts.actor !== void 0 ? { actor: opts.actor } : {},
		limit
	});
	console.log(SEP);
	console.log(" DatasynxOpenCRM — Audit Trail");
	if (opts.slug) console.log(` Customer: ${opts.slug}`);
	if (opts.actor) console.log(` Actor:    ${opts.actor}`);
	console.log(SEP);
	if (entries.length === 0) {
		console.log(" No audit entries found.");
		console.log(SEP);
		return;
	}
	for (const entry of entries) console.log(` ${entry.timestamp}  ${entry.actor.padEnd(12)}  ${entry.tool.padEnd(20)}  ${entry.slug.padEnd(20)}  ${entry.summary}`);
	console.log(SEP);
	console.log(` ${entries.length} entr${entries.length === 1 ? "y" : "ies"} shown`);
	console.log(SEP);
}
new Command("audit").description("Show CRM audit trail — who changed what and when").option("--slug <slug>", "Filter by customer slug").option("--actor <actor>", "Filter by actor").option("--limit <n>", "Number of entries to show (default: 20)", parseInt).option("--tail", "Show all new entries (simplified: shows current entries)").action((opts) => runAudit(opts, process.env["DXCRM_DATA_DIR"]));
//#endregion
//#region src/commands/validate.ts
const RECOVERABLE_DEFAULTS = {
	tags: [],
	currency: "EUR"
};
function applyFix(factsPath, content, data) {
	const fixed = [];
	const patched = { ...data };
	for (const [field, defaultValue] of Object.entries(RECOVERABLE_DEFAULTS)) if (patched[field] === void 0 || patched[field] === null) {
		patched[field] = defaultValue;
		fixed.push(`${field} → ${JSON.stringify(defaultValue)}`);
	}
	if (patched["updated"] === void 0 && patched["created"]) {
		patched["updated"] = patched["created"];
		fixed.push(`updated → ${String(patched["created"])}`);
	}
	if (fixed.length === 0) return null;
	const parsed = matter(content);
	const newContent = matter.stringify(parsed.content, patched);
	fs.writeFileSync(factsPath, newContent);
	return {
		fixed,
		content: newContent
	};
}
async function runValidate(opts, dataDir) {
	const customersDir = path.join(dataDir, "customers");
	if (!fs.existsSync(customersDir)) {
		console.log(warning("⚠ No customers directory found."));
		return;
	}
	const slugs = listCustomerSlugs(dataDir);
	let errorCount = 0;
	let fixedCount = 0;
	for (const slug of slugs) {
		const factsPath = path.join(customersDir, slug, "main_facts.md");
		const interactionsPath = path.join(customersDir, slug, "interactions.md");
		if (!fs.existsSync(factsPath)) {
			console.log(error(`✗ ${slug}: missing main_facts.md`));
			errorCount++;
			continue;
		}
		try {
			let content = fs.readFileSync(factsPath, "utf-8");
			let parsed = matter(content);
			if (opts.fix) {
				const result = applyFix(factsPath, content, parsed.data);
				if (result) {
					content = result.content;
					parsed = matter(content);
					fixedCount++;
					console.log(info(`⚙ ${slug}: fixed ${result.fixed.join(", ")}`));
				}
			}
			MainFactsSchema.parse(parsed.data);
			if (!fs.existsSync(interactionsPath)) console.log(warning(`⚠ ${slug}: missing interactions.md`));
			else console.log(success(`✓ ${slug}`));
		} catch (err) {
			console.log(error(`✗ ${slug}: ${err.message}`));
			errorCount++;
		}
	}
	if (opts.fix && fixedCount > 0) console.log(info(`\n⚙ Fixed ${fixedCount} customer(s).`));
	if (errorCount > 0) {
		console.error(error(`\n${errorCount} error(s) found.`));
		process.exit(1);
	} else console.log(success("\n✓ All customers valid."));
}
new Command("validate").description("Validate all customer data against schemas").option("--fix", "Auto-fix recoverable issues").action(async (opts) => {
	await runValidate(opts, process.env["DXCRM_DATA_DIR"] ?? process.cwd());
});
//#endregion
//#region src/version.ts
const VERSION = "0.1.0";
//#endregion
export { VERSION, canSeeCustomer, clearSession, createCustomer, customerExists, filterAuditLog, getRbacConfig, getRole, getSession, readAuditLog, readMainFacts, runAudit, runBackup, runValidate, setSession };

//# sourceMappingURL=index.js.map