import { accessSync, chmodSync, constants, existsSync, mkdirSync, statSync } from "node:fs";
import { join } from "node:path";
//#region src/cli/commands/doctor/checks/state-integrity.ts
function isWritable(dir) {
	try {
		accessSync(dir, constants.W_OK);
		return true;
	} catch {
		return false;
	}
}
async function checkStateIntegrity(ctx) {
	const root = ctx.stateDir;
	const hints = [];
	if (!existsSync(root)) {
		if (ctx.options.fix) try {
			mkdirSync(root, {
				recursive: true,
				mode: 448
			});
			if (process.platform !== "win32") chmodSync(root, 448);
			return {
				id: "state-integrity",
				label: "State directory",
				status: "pass",
				message: "Created state directory with safe permissions.",
				hints: [root],
				fixed: true
			};
		} catch (e) {
			return {
				id: "state-integrity",
				label: "State directory",
				status: "fail",
				message: `State directory missing and could not create: ${e instanceof Error ? e.message : String(e)}`,
				hints: [root]
			};
		}
		return {
			id: "state-integrity",
			label: "State directory",
			status: "fail",
			message: "State directory does not exist.",
			hints: [
				`Expected: ${root}`,
				"Run: xopc init (or xopc setup)",
				"Or: xopc doctor --fix"
			]
		};
	}
	if (!isWritable(root)) return {
		id: "state-integrity",
		label: "State directory",
		status: "fail",
		message: "State directory is not writable.",
		hints: [root]
	};
	if (process.platform !== "win32") try {
		if ((statSync(root).mode & 511) !== 448) {
			if (ctx.options.fix) {
				chmodSync(root, 448);
				return {
					id: "state-integrity",
					label: "State directory",
					status: "pass",
					message: "State directory permissions set to 700.",
					hints: [root],
					fixed: true
				};
			}
			return {
				id: "state-integrity",
				label: "State directory",
				status: "warn",
				message: "State directory permissions are not 700 (recommended for privacy).",
				hints: [root, "Run: xopc doctor --fix"]
			};
		}
	} catch {}
	const agentsDir = join(root, "agents");
	if (!existsSync(agentsDir) && ctx.options.fix) try {
		mkdirSync(agentsDir, {
			recursive: true,
			mode: 448
		});
		hints.push(`Created: ${agentsDir}`);
	} catch {}
	return {
		id: "state-integrity",
		label: "State directory",
		status: "pass",
		message: "State directory exists and is usable.",
		hints: hints.length ? hints : [root]
	};
}
//#endregion
export { checkStateIntegrity };

//# sourceMappingURL=state-integrity.js.map