import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { join } from "node:path";
//#region extensions/crypto/src/services/mode-service.ts
/**
* Mode service — tracks per-user safety mode and signing mode.
*
* Two independent toggles:
* 1. Intent confirmation: safe (confirm before acting) / danger (act immediately) / readonly (view only, no writes)
* 2. Signing method: wallet (WalletConnect, phone approval) / autosign (private key)
*
* State persists on volume alongside onboarding state.
*/
function getStateDir() {
	return process.env.OPENCLAWNCH_TX_DIR ? join(process.env.OPENCLAWNCH_TX_DIR, "..", "modes") : join(process.env.HOME ?? "/tmp", ".openclawnch", "modes");
}
function ensureDir() {
	const dir = getStateDir();
	if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
}
function sanitizeUserId(userId) {
	const safe = userId.replace(/[^a-zA-Z0-9_\-\.]/g, "_");
	if (safe.includes("..") || safe.includes("/") || safe.includes("\\")) return "invalid_user";
	return safe.slice(0, 64);
}
function modePath(userId) {
	return join(getStateDir(), `${sanitizeUserId(userId)}.json`);
}
function loadMode(userId) {
	try {
		const path = modePath(userId);
		if (existsSync(path)) return JSON.parse(readFileSync(path, "utf8"));
	} catch {}
	return {
		userId,
		safetyMode: "safe",
		signingMode: "wallet",
		lastChanged: Date.now()
	};
}
function saveMode(mode) {
	ensureDir();
	writeFileSync(modePath(mode.userId), JSON.stringify(mode, null, 2), "utf8");
}
const cache = /* @__PURE__ */ new Map();
function getUserMode(userId) {
	let mode = cache.get(userId);
	if (!mode) {
		mode = loadMode(userId);
		cache.set(userId, mode);
	}
	return mode;
}
function setSafetyMode(userId, safetyMode) {
	const mode = getUserMode(userId);
	mode.safetyMode = safetyMode;
	mode.lastChanged = Date.now();
	cache.set(userId, mode);
	saveMode(mode);
	return mode;
}
function setSigningMode(userId, signingMode) {
	const mode = getUserMode(userId);
	mode.signingMode = signingMode;
	mode.lastChanged = Date.now();
	cache.set(userId, mode);
	saveMode(mode);
	return mode;
}
/**
* Check if a user is in readonly mode (no on-chain writes allowed).
*/
function isReadonly(userId) {
	return getUserMode(userId).safetyMode === "readonly";
}
function resetModes() {
	cache.clear();
}
//#endregion
export { getUserMode, isReadonly, resetModes, setSafetyMode, setSigningMode };

//# sourceMappingURL=mode-service.mjs.map