import { r as __require } from "../../chunk-BEJ448es.mjs";
import { getWalletState } from "../services/walletconnect-service.mjs";
import { describeRule, getPolicyMode, isDelegationMode } from "../services/policy-types.mjs";
import { getPolicyStore } from "../services/policy-store.mjs";
import { buildPolicyDisplay, renderPolicyDisplay } from "../services/policy-evaluator.mjs";
import { CHAIN_NAMES } from "../services/delegation-types.mjs";
import { canRedeem, formatDelegationStatus } from "../services/delegation-service.mjs";
import { recordCommand } from "../services/command-history.mjs";
import { hasAgentAccount } from "../services/agent-keystore.mjs";
//#region extensions/crypto/src/commands/policies-command.ts
/**
* /policies — User-facing command for viewing and managing spending policies.
*
* Subcommands:
*   /policies              — list all policies with their rules
*   /policies <name>       — view a specific policy
*   /policies enable <name>
*   /policies disable <name>
*   /policies delete <name>
*
* Policy CREATION is handled conversationally via the policy_manage tool.
* Users just say what they want in plain English; the agent interprets.
*/
/** Determine actual enforcement based on wallet mode + delegation setup. */
function getEnforcementInfo() {
	const wallet = getWalletState();
	const hasAgent = hasAgentAccount();
	if (wallet.mode === "bankr") return {
		method: "AI-enforced (Bankr wallet)",
		explanation: hasAgent ? "Your Bankr wallet sends transactions through its own API. Policies are enforced by the AI before execution — not on-chain. To use on-chain enforcement, send from your delegator account instead." : "Your Bankr wallet sends transactions through its own API. Policies are enforced by the AI before execution — not on-chain. Run /delegator create to set up on-chain enforcement with a separate smart account."
	};
	if (hasAgent) return {
		method: "On-chain (delegator smart account)",
		explanation: "Transactions from the delegator account are enforced on-chain by smart contract caveats. The agent cannot bypass these limits."
	};
	return {
		method: "AI-enforced (no delegator set up)",
		explanation: "Policies are enforced by the AI before execution. Run /delegator create for tamper-proof on-chain enforcement."
	};
}
const policiesCommand = {
	name: "policies",
	description: "View and manage spending policies: /policies [enable|disable|delete] [name]",
	acceptsArgs: true,
	requireAuth: true,
	handler: async (ctx) => {
		const args = (ctx?.args ?? "").trim();
		const store = getPolicyStore();
		const { extractPolicyUserId } = await import("../services/policy-evaluator.mjs");
		let userId = extractPolicyUserId(ctx);
		if (store.listPolicies(userId).length === 0) {
			const found = store.findFirstUserWithPolicies();
			if (found) {
				const foundCount = store.listPolicies(found).length;
				console.info(`[policies] userId=${userId} has 0 policies, found=${found} has ${foundCount}`);
				if (foundCount > 0) userId = found;
			} else console.info(`[policies] userId=${userId} has 0 policies, no alternative found`);
		}
		let result;
		if (!args) result = listAll(userId);
		else {
			const parts = args.split(/\s+/);
			const sub = parts[0].toLowerCase();
			const name = parts.slice(1).join(" ");
			switch (sub) {
				case "create":
					result = createQuick(userId, name);
					break;
				case "enable":
					result = setStatus(userId, name, "active");
					break;
				case "disable":
					result = setStatus(userId, name, "disabled");
					break;
				case "delete":
					result = deletePol(userId, name);
					break;
				case "overview":
					result = showOverview(userId);
					break;
				default:
					result = viewPolicy(userId, args);
					break;
			}
		}
		recordCommand(userId, `/policies ${args}`.trim(), result.text.slice(0, 150));
		return result;
	}
};
function createQuick(userId, nameAndAmount) {
	const parts = nameAndAmount.trim().split(/\s+/);
	const name = parts[0];
	const amountStr = parts[1];
	if (!name || !amountStr) return { text: [
		"Usage: /policies create <name> <max-usd>",
		"",
		"Example:",
		"  /policies create test-live 5",
		"  (blocks any tx over $5)",
		"",
		"  /policies create daily-cap 100",
		"  (blocks any tx over $100)"
	].join("\n") };
	const maxUsd = parseFloat(amountStr);
	if (isNaN(maxUsd) || maxUsd <= 0) return { text: `Invalid amount: ${amountStr}. Use a positive number (USD).` };
	const store = getPolicyStore();
	if (store.getPolicyByName(userId, name)) return { text: `Policy "${name}" already exists. Use /policies delete ${name} first.` };
	const { randomUUID } = __require("node:crypto");
	const policy = {
		id: randomUUID(),
		name,
		description: `Max $${maxUsd} per transaction`,
		rules: [{
			type: "max_amount",
			maxAmountUsd: maxUsd
		}],
		scope: { type: "all_write" },
		status: "active",
		confirmedAt: Date.now(),
		createdAt: Date.now(),
		updatedAt: Date.now(),
		userId
	};
	store.savePolicy(policy);
	return { text: [
		`**Policy "${name}" created and active.**`,
		"",
		`  Rule: block any tx over $${maxUsd}`,
		"  Scope: all write operations",
		"",
		"Next: /delegate create " + name
	].join("\n") };
}
function listAll(userId) {
	const policies = getPolicyStore().listPolicies(userId);
	if (policies.length === 0) return { text: [
		"**No policies set.**",
		"",
		"To create a policy, just describe what you want in plain English:",
		"  \"Don't let me spend more than $500 a day on DeFi\"",
		"  \"Block all interactions with SHIB\"",
		"  \"Require my confirmation for anything over $100\"",
		"",
		"The agent will interpret your request, show you exactly what will be enforced, and ask for confirmation before activating."
	].join("\n") };
	const modeLabel = getPolicyMode() === "delegation" ? "delegation (on-chain)" : "simple (app-layer)";
	const lines = [`**${policies.length} polic${policies.length === 1 ? "y" : "ies"}** — mode: ${modeLabel}`, ""];
	for (const p of policies) {
		const display = buildPolicyDisplay(p, userId);
		lines.push(renderPolicyDisplay(display));
		if (p.delegation && isDelegationMode()) {
			lines.push("");
			lines.push("**On-chain delegation:**");
			lines.push(formatDelegationStatus(p.delegation));
		}
		lines.push("");
		lines.push("---");
		lines.push("");
	}
	lines.push("Commands: `/policies enable <name>`, `/policies disable <name>`, `/policies delete <name>`");
	return { text: lines.join("\n") };
}
function viewPolicy(userId, nameOrId) {
	const store = getPolicyStore();
	let policy = store.getPolicyByName(userId, nameOrId);
	if (!policy) policy = store.getPolicy(userId, nameOrId);
	if (!policy) return { text: `Policy "${nameOrId}" not found. Use \`/policies\` to list all.` };
	const lines = [renderPolicyDisplay(buildPolicyDisplay(policy, userId))];
	if (isDelegationMode() && policy.delegation) {
		lines.push("");
		lines.push("**On-chain delegation:**");
		lines.push(formatDelegationStatus(policy.delegation));
		if (policy.delegation.expiresAt) {
			const exp = new Date(policy.delegation.expiresAt);
			const remaining = exp.getTime() - Date.now();
			if (remaining > 0) {
				const hours = Math.floor(remaining / 36e5);
				const days = Math.floor(hours / 24);
				lines.push(`  Expires: ${exp.toISOString()} (${days > 0 ? `${days}d ` : ""}${hours % 24}h remaining)`);
			} else lines.push("  Expires: **EXPIRED**");
		}
	}
	return { text: lines.join("\n") };
}
function showOverview(userId) {
	const store = getPolicyStore();
	const policies = store.listPolicies(userId);
	getPolicyMode();
	const delegation = isDelegationMode();
	const lines = [];
	lines.push("**Policy Overview**");
	lines.push("");
	const enforcement = getEnforcementInfo();
	lines.push(`Enforced by: **${enforcement.method}**`);
	lines.push(enforcement.explanation);
	lines.push("");
	const active = policies.filter((p) => p.status === "active");
	const withDelegation = active.filter((p) => p.delegation?.status === "signed" || p.delegation?.status === "active");
	lines.push(`Policies: ${active.length} active${withDelegation.length > 0 ? `, ${withDelegation.length} with on-chain delegation` : ""}`);
	lines.push("");
	if (active.length === 0) {
		lines.push("No active policies. Describe a policy in plain English and the agent will create it.");
		return { text: lines.join("\n") };
	}
	for (const p of active) {
		const rules = p.rules.map((r) => describeRule(r));
		const scopeLabel = p.scope.type === "all_write" ? "all write tools" : p.scope.type === "tools" ? p.scope.tools?.join(", ") : p.scope.type === "categories" ? p.scope.categories?.join(", ") : p.scope.type;
		lines.push(`**${p.name}**`);
		lines.push(`  Scope: ${scopeLabel}`);
		for (const r of rules) lines.push(`  Rule: ${r}`);
		const usage = store.getUsage?.(userId, p.id);
		if (usage) {
			for (const u of Array.isArray(usage) ? usage : []) if (u.spentUsd !== void 0 && u.limitUsd !== void 0) {
				const pct = Math.round(u.spentUsd / u.limitUsd * 100);
				const remaining = Math.max(0, u.limitUsd - u.spentUsd);
				lines.push(`  Budget: $${u.spentUsd.toFixed(2)} / $${u.limitUsd} used (${pct}%, $${remaining.toFixed(2)} remaining)`);
			}
		}
		if (delegation && p.delegation) {
			const d = p.delegation;
			const chain = CHAIN_NAMES[d.chainId] ?? d.chainId;
			const statusTag = canRedeem(p.id).ready ? "READY" : "NOT READY";
			let expiryTag = "";
			if (d.expiresAt) {
				const remaining = new Date(d.expiresAt).getTime() - Date.now();
				if (remaining <= 0) expiryTag = " | EXPIRED";
				else {
					const h = Math.floor(remaining / 36e5);
					expiryTag = h >= 24 ? ` | ${Math.floor(h / 24)}d remaining` : ` | ${h}h remaining`;
				}
			}
			lines.push(`  Delegation: [${d.status.toUpperCase()}] on ${chain} | ${statusTag}${expiryTag}`);
		} else if (delegation) lines.push("  Delegation: none (use `/delegate create ${p.name}`)");
		lines.push("");
	}
	lines.push("---");
	lines.push("`/policies <name>` for details | `/delegate status` for on-chain state");
	return { text: lines.join("\n") };
}
function setStatus(userId, name, status) {
	if (!name) return { text: `Usage: \`/policies ${status === "active" ? "enable" : "disable"} <name>\`` };
	const store = getPolicyStore();
	let policy = store.getPolicyByName(userId, name);
	if (!policy) policy = store.getPolicy(userId, name);
	if (!policy) return { text: `Policy "${name}" not found.` };
	policy.status = status;
	policy.updatedAt = Date.now();
	store.savePolicy(policy);
	const label = status === "active" ? "enabled (active)" : "disabled";
	return { text: `Policy **${policy.name}** is now ${label}.` };
}
function deletePol(userId, name) {
	if (!name) return { text: "Usage: `/policies delete <name>`" };
	const store = getPolicyStore();
	let policy = store.getPolicyByName(userId, name);
	if (!policy) policy = store.getPolicy(userId, name);
	if (!policy) return { text: `Policy "${name}" not found.` };
	store.deletePolicy(userId, policy.id);
	return { text: `Policy **${policy.name}** has been deleted.` };
}
//#endregion
export { policiesCommand };

//# sourceMappingURL=policies-command.mjs.map