import { _ as resolveStateDir } from "./paths-C9FmTW1x.js";
import fs from "node:fs";
import path from "node:path";

//#region src/wallet/wallet-runtime-config.ts
const DEFAULT_WALLET_RUNTIME_PORT = 19444;
const DEFAULT_WALLET_RUNTIME_HOST = "127.0.0.1";
const DEFAULT_WALLET_RUNTIME_VERSION = "0.1.1";
const DEFAULT_WALLET_RUNTIME_SOURCE_REF = "v0.2.30";
const DEFAULT_POLICY_CAPS = { solana: {
	maxPerTx: "1000000000",
	maxDaily: "5000000000"
} };
function normalizeChainList(chains) {
	const out = /* @__PURE__ */ new Set();
	for (const chain of chains ?? []) if (chain === "solana") out.add(chain);
	if (out.size === 0) out.add("solana");
	return [...out];
}
function parsePositiveBigInt(raw, fallback) {
	const input = raw?.trim() || fallback;
	try {
		const value = BigInt(input);
		return value >= 0n ? value : BigInt(fallback);
	} catch {
		return BigInt(fallback);
	}
}
function normalizeSolanaTokenCaps(raw) {
	if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {};
	const out = {};
	for (const [mintRaw, capRaw] of Object.entries(raw)) {
		const mint = mintRaw.trim();
		if (!mint || !capRaw || typeof capRaw !== "object" || Array.isArray(capRaw)) continue;
		const cap = capRaw;
		out[mint] = {
			maxPerTx: parsePositiveBigInt(typeof cap.maxPerTx === "string" ? cap.maxPerTx : void 0, "0"),
			maxDaily: parsePositiveBigInt(typeof cap.maxDaily === "string" ? cap.maxDaily : void 0, "0")
		};
	}
	return out;
}
function isPositivePolicyAmount(raw) {
	if (typeof raw !== "string") return false;
	try {
		return BigInt(raw.trim() || "0") > 0n;
	} catch {
		return false;
	}
}
function hasExplicitPositiveCaps(policy) {
	if (!policy || typeof policy !== "object" || Array.isArray(policy)) return false;
	const value = policy;
	const solana = value.solana && typeof value.solana === "object" ? value.solana : {};
	if (isPositivePolicyAmount(solana.maxPerTx) || isPositivePolicyAmount(solana.maxDaily)) return true;
	const tokenCaps = solana.tokenCaps && typeof solana.tokenCaps === "object" && !Array.isArray(solana.tokenCaps) ? solana.tokenCaps : {};
	return Object.values(tokenCaps).some((capRaw) => {
		const cap = capRaw && typeof capRaw === "object" ? capRaw : {};
		return isPositivePolicyAmount(cap.maxPerTx) || isPositivePolicyAmount(cap.maxDaily);
	});
}
function resolveWalletStatePaths(env = process.env) {
	const rootDir = path.join(resolveStateDir(env), "wallet");
	const stackRootDir = path.join(rootDir, "wallet-stack");
	return {
		rootDir,
		keysPath: path.join(rootDir, "wallet-keys.json"),
		dailyUsagePath: path.join(rootDir, "policy-usage.json"),
		sendApprovalsPath: path.join(rootDir, "wallet-send-approvals.json"),
		auditLogPath: path.join(rootDir, "wallet-audit.jsonl"),
		sidecarPidPath: path.join(rootDir, "wallet-service.pid"),
		sidecarLogPath: path.join(rootDir, "wallet-service.log"),
		sidecarMetaPath: path.join(rootDir, "wallet-service.meta.json"),
		stackRootDir,
		stackComposePath: path.join(stackRootDir, "docker-compose.yml"),
		stackEnvPath: path.join(stackRootDir, ".env")
	};
}
function ensureWalletStateDir(env = process.env) {
	const paths = resolveWalletStatePaths(env);
	fs.mkdirSync(paths.rootDir, {
		recursive: true,
		mode: 448
	});
	try {
		fs.chmodSync(paths.rootDir, 448);
	} catch {}
	return paths;
}
function resolveLocalSignerSocketPath(env = process.env) {
	const explicit = String(env.FASED_WALLET_LOCAL_SIGNER_SOCKET ?? "").trim();
	if (explicit) return path.resolve(explicit);
	return path.join(ensureWalletStateDir(env).rootDir, "local-signer.sock");
}
function resolveLocalSignerSidecarPaths(socketPath) {
	const resolvedSocketPath = path.resolve(socketPath);
	const socketDir = path.dirname(resolvedSocketPath);
	const socketName = path.basename(resolvedSocketPath);
	const sidecarBaseName = socketName.endsWith(".sock") ? socketName.slice(0, -5) : socketName;
	return {
		pidPath: path.join(socketDir, `${sidecarBaseName}.pid`),
		auditPath: path.join(socketDir, `${sidecarBaseName}.audit.jsonl`)
	};
}
function resolveLocalSignerMaterialRootDir(env = process.env) {
	const explicit = String(env.FASED_WALLET_SIGNER_STATE_DIR ?? "").trim();
	if (explicit) return path.resolve(explicit);
	return ensureWalletStateDir(env).rootDir;
}
function resolveLocalSignerBackendSocketPath(env = process.env) {
	const explicit = String(env.FASED_WALLET_LOCAL_SIGNER_BACKEND_SOCKET ?? "").trim();
	if (explicit) return path.resolve(explicit);
	return resolveLocalSignerSocketPath(env);
}
function resolveLocalSignerRunAsUser(env = process.env) {
	return String(env.FASED_WALLET_LOCAL_SIGNER_RUN_AS_USER ?? "").trim() || void 0;
}
function parseRuntime(value) {
	switch (value) {
		case "external-docker":
		case "external-custom": return value;
		default: return null;
	}
}
function resolveRuntime(params) {
	const parsed = parseRuntime(params.explicitRuntime);
	if (parsed) return parsed;
	if (params.legacyMode === "external") return params.externalKind === "docker" ? "external-docker" : "external-custom";
	return "external-docker";
}
function inferDefaultWalletProviderId(env) {
	if (String(env.FASED_WALLET_LOCAL_SIGNER_SOCKET ?? "").trim()) return "local-socket-signer";
	for (const key of Object.keys(env)) if (key === "FASED_WALLET_SOLANA_KEYSTORE_PATH" || key === "FASED_WALLET_PASSPHRASE_FILE" || key.startsWith("FASED_WALLET_SOLANA_KEYSTORE_PATH__")) {
		if (String(env[key] ?? "").trim()) return "local-socket-signer";
	}
	return null;
}
function resolveWalletRuntimeConfig(cfg, env = process.env) {
	const managedProfile = (env.FASED_GATEWAY_MODE ?? "").trim().toLowerCase() === "managed";
	const walletRuntime = cfg.wallet?.runtime;
	const providerId = cfg.wallet?.provider?.id ?? inferDefaultWalletProviderId(env) ?? "local-socket-signer";
	const enabled = walletRuntime?.enabled ?? managedProfile;
	const legacyMode = walletRuntime?.mode === "external" ? "external" : "managed";
	const runtime = resolveRuntime({
		explicitRuntime: walletRuntime?.runtime,
		legacyMode,
		providerId,
		externalKind: walletRuntime?.external?.kind
	});
	const mode = "external";
	const chains = normalizeChainList(walletRuntime?.chains);
	const host = walletRuntime?.service?.host?.trim() || DEFAULT_WALLET_RUNTIME_HOST;
	const port = typeof walletRuntime?.service?.port === "number" && Number.isFinite(walletRuntime.service.port) && walletRuntime.service.port > 0 && walletRuntime.service.port <= 65535 ? Math.floor(walletRuntime.service.port) : DEFAULT_WALLET_RUNTIME_PORT;
	const installEnabled = walletRuntime?.install?.enabled ?? managedProfile;
	const installVersion = walletRuntime?.install?.version?.trim() || DEFAULT_WALLET_RUNTIME_VERSION;
	const paths = resolveWalletStatePaths(env);
	const externalKind = walletRuntime?.external?.kind === "custom" || runtime === "external-custom" ? "custom" : "docker";
	const authModeRaw = walletRuntime?.auth?.mode;
	const authMode = authModeRaw === "jwt-bootstrap" || authModeRaw === "static-token-compat" ? authModeRaw : "static-token-compat";
	const bootstrapUrl = walletRuntime?.auth?.bootstrapUrl?.trim() || String(env.FASED_WALLET_AUTH_BOOTSTRAP_URL ?? "").trim() || void 0;
	const sourceRef = walletRuntime?.source?.ref?.trim() || String(env.FASED_WALLET_SOURCE_REF ?? "").trim() || DEFAULT_WALLET_RUNTIME_SOURCE_REF;
	const toolAccessModeRaw = walletRuntime?.toolAccess?.mode;
	const toolAccessMode = toolAccessModeRaw === "all" || toolAccessModeRaw === "allowlist" ? toolAccessModeRaw : "owner-only";
	const allowAgents = (walletRuntime?.toolAccess?.allowAgents ?? []).map((value) => String(value).trim()).filter(Boolean);
	const allowSkills = (walletRuntime?.toolAccess?.allowSkills ?? []).map((value) => String(value).trim()).filter(Boolean);
	const denySkills = (walletRuntime?.toolAccess?.denySkills ?? []).map((value) => String(value).trim()).filter(Boolean);
	const allowSources = (walletRuntime?.toolAccess?.allowSources ?? []).map((value) => String(value).trim().toLowerCase()).filter(Boolean);
	return {
		enabled,
		mode,
		runtime,
		execution: { mode: cfg.wallet?.execution?.mode === "autonomous" || cfg.wallet?.execution?.mode !== "manual" && (walletRuntime?.policy?.directSigning ?? true) ? "autonomous" : "manual" },
		chains,
		service: {
			host,
			port
		},
		install: {
			enabled: installEnabled,
			version: installVersion
		},
		external: { kind: externalKind },
		auth: {
			mode: authMode,
			bootstrapUrl
		},
		source: { ref: sourceRef },
		stack: {
			rootDir: paths.stackRootDir,
			composePath: paths.stackComposePath,
			envPath: paths.stackEnvPath,
			projectName: "fased-wallet"
		},
		policy: {
			capsEnabled: typeof walletRuntime?.policy?.capsEnabled === "boolean" ? walletRuntime.policy.capsEnabled : hasExplicitPositiveCaps(walletRuntime?.policy),
			directSigning: walletRuntime?.policy?.directSigning ?? true,
			skillsEnabled: walletRuntime?.policy?.skillsEnabled === true,
			solana: {
				allowPrograms: (walletRuntime?.policy?.solana?.allowPrograms ?? []).map((value) => String(value).trim()).filter(Boolean),
				caps: {
					maxPerTx: parsePositiveBigInt(walletRuntime?.policy?.solana?.maxPerTx, DEFAULT_POLICY_CAPS.solana.maxPerTx),
					maxDaily: parsePositiveBigInt(walletRuntime?.policy?.solana?.maxDaily, DEFAULT_POLICY_CAPS.solana.maxDaily)
				},
				tokenCaps: normalizeSolanaTokenCaps(walletRuntime?.policy?.solana?.tokenCaps)
			}
		},
		toolAccess: {
			mode: toolAccessMode,
			allowAgents,
			allowSkills,
			denySkills,
			allowSources
		}
	};
}

//#endregion
export { resolveLocalSignerSidecarPaths as a, resolveWalletStatePaths as c, resolveLocalSignerRunAsUser as i, resolveLocalSignerBackendSocketPath as n, resolveLocalSignerSocketPath as o, resolveLocalSignerMaterialRootDir as r, resolveWalletRuntimeConfig as s, ensureWalletStateDir as t };