import "./paths-C9FmTW1x.js";
import { U as theme } from "./agent-paths-BySKyq9I.js";
import { dd as formatCliCommand } from "./agent-scope-CLn_Ws3B.js";
import { d as defaultRuntime } from "./errors-Dx3S3Nrp.js";
import "./github-copilot-token-BA45-q56.js";
import "./chat-envelope-D_wSv26N.js";
import "./pairing-token-BFGorDQo.js";
import "./ip-D_T5zbZS.js";
import "./ws-cvQhrVP3.js";
import "./device-identity-DzUZ06fL.js";
import "./call-s6DNIELo.js";
import { n as runCommandWithRuntime } from "./cli-utils-DJ7Nfw8J.js";
import { t as formatHelpExamples } from "./help-format-H4GNCFCs.js";
import "./progress-CDqdg8f8.js";
import { n as callGatewayFromCli, t as addGatewayClientOptions } from "./gateway-rpc-C9uKnQRG.js";

//#region src/cli/mining-cli.ts
const LAMPORTS_PER_SOL = 1000000000n;
function runMiningCommand(action, label) {
	return runCommandWithRuntime(defaultRuntime, action, (err) => {
		const message = err instanceof Error ? err.message : String(err);
		defaultRuntime.error(label ? `${label}: ${message}` : message);
		defaultRuntime.exit(1);
	});
}
function renderResult(result, opts, successText) {
	if (opts.json || successText === void 0) {
		defaultRuntime.log(JSON.stringify(result, null, 2));
		return;
	}
	defaultRuntime.log(successText);
}
async function runMiningGatewayCommand(method, opts, params, successText, extra) {
	const result = await callGatewayFromCli(method, opts, params, { expectFinal: extra?.expectFinal ?? false });
	if (extra?.render !== false) renderResult(result, opts, successText);
	return result;
}
function asRecord(value) {
	if (!value || typeof value !== "object" || Array.isArray(value)) return;
	return value;
}
function extractGatewayPayload(result) {
	let current = result;
	for (let index = 0; index < 3; index += 1) {
		const record = asRecord(current);
		if (!record || !("payload" in record)) return current;
		current = record.payload;
	}
	return current;
}
function readBoolean(record, key) {
	const value = record?.[key];
	return typeof value === "boolean" ? value : void 0;
}
function readMiningGatewayStatus(result) {
	const payload = asRecord(extractGatewayPayload(result)) ?? {};
	return {
		payload,
		status: asRecord(payload.status)
	};
}
function readMiningStatusDetail(status) {
	for (const key of [
		"nextActionDetail",
		"bootstrapReason",
		"blockedReason"
	]) {
		const value = status?.[key];
		if (typeof value === "string" && value.trim()) return value.trim();
	}
	return "No status detail returned.";
}
function renderMiningStartResult(result, opts) {
	if (opts.json) {
		renderResult(result, opts);
		return;
	}
	const { payload, status } = readMiningGatewayStatus(result);
	const running = readBoolean(status, "running") === true;
	const drainOnly = readBoolean(status, "drainOnly") === true;
	const enabledWanted = readBoolean(status, "enabledWanted");
	if (!(payload.started === true && running && !drainOnly && enabledWanted !== false)) throw new Error(`Start was requested, but SAT mining is not running. ${readMiningStatusDetail(status)}`);
	defaultRuntime.log("SAT mining started");
}
function renderMiningStopResult(result, opts) {
	if (opts.json) {
		renderResult(result, opts);
		return;
	}
	const { payload, status } = readMiningGatewayStatus(result);
	const running = readBoolean(status, "running") === true;
	const drainOnly = readBoolean(status, "drainOnly") === true;
	if (payload.stopped === true && !running) {
		defaultRuntime.log("SAT mining stopped");
		return;
	}
	if (payload.stopped === true && drainOnly) {
		defaultRuntime.log("New SAT mining cycles stopped; drain/recovery remains active until locked capital is free.");
		return;
	}
	throw new Error(`Stop was requested, but SAT mining is still running. ${readMiningStatusDetail(status)}`);
}
function parsePositiveInt(raw, label) {
	if (!raw) return;
	const parsed = Number.parseInt(raw, 10);
	if (!Number.isFinite(parsed) || parsed <= 0) throw new Error(`${label} must be a positive integer`);
	return parsed;
}
function normalizeWalletId(raw) {
	const walletId = typeof raw === "string" ? raw.trim() : "";
	return walletId ? walletId : void 0;
}
function parseLamportsInput(opts) {
	const lamportsRaw = typeof opts.lamports === "string" ? opts.lamports.trim() : "";
	const solRaw = typeof opts.sol === "string" ? opts.sol.trim() : "";
	if (lamportsRaw && solRaw) throw new Error("Use either --sol or --lamports, not both");
	if (lamportsRaw) {
		if (!/^\d+$/.test(lamportsRaw)) throw new Error("--lamports must be a non-negative integer string");
		return lamportsRaw;
	}
	if (!solRaw) throw new Error("One of --sol or --lamports is required");
	if (!/^\d+(\.\d{0,9})?$/.test(solRaw)) throw new Error("--sol must be a non-negative number with up to 9 decimal places");
	const [wholePart, fractionPart = ""] = solRaw.split(".");
	return (BigInt(wholePart || "0") * LAMPORTS_PER_SOL + BigInt((fractionPart + "000000000").slice(0, 9) || "0")).toString();
}
function registerMiningCli(program) {
	const mining = program.command("mining").description("Operate SAT mining without going through the Control UI").addHelpText("after", () => `\n${theme.heading("Examples:")}\n${formatHelpExamples([
		[formatCliCommand("fased mining status"), "Show live mining status and issuance state."],
		[formatCliCommand("fased mining start --wallet solana-1"), "Start SAT mining for an explicit wallet id."],
		[formatCliCommand("fased mining deposit-capital --sol 1"), "Move 1 SOL into miner capital."],
		[formatCliCommand("fased mining set-commit --sol 0.75"), "Set the active SAT commit amount."]
	])}\n`);
	addGatewayClientOptions(mining.command("status").description("Show live SAT mining status").option("--json", "Output JSON", false)).action(async (opts) => {
		await runMiningCommand(async () => {
			await runMiningGatewayCommand("sat.getMiningStatus", opts);
		}, "Mining status failed");
	});
	addGatewayClientOptions(mining.command("readiness").description("Show SAT mining readiness for the selected or provided wallet").option("--wallet <walletId>", "Wallet id to inspect").option("--json", "Output JSON", false)).action(async (opts) => {
		await runMiningCommand(async () => {
			await runMiningGatewayCommand("sat.getMiningReadiness", opts, { walletId: normalizeWalletId(opts.wallet) });
		}, "Mining readiness failed");
	});
	addGatewayClientOptions(mining.command("wallets").description("List mining-eligible wallets").option("--json", "Output JSON", false)).action(async (opts) => {
		await runMiningCommand(async () => {
			await runMiningGatewayCommand("sat.listMiningWallets", opts);
		}, "Mining wallet list failed");
	});
	addGatewayClientOptions(mining.command("start").description("Start SAT mining for the active or provided wallet").option("--wallet <walletId>", "Wallet id to attach before starting").option("--json", "Output JSON", false)).action(async (opts) => {
		await runMiningCommand(async () => {
			renderMiningStartResult(await runMiningGatewayCommand("sat.startMining", {
				...opts,
				timeout: opts.timeout === "30000" || opts.timeout == null ? "90000" : opts.timeout
			}, { walletId: normalizeWalletId(opts.wallet) }, void 0, {
				expectFinal: true,
				render: false
			}), opts);
		}, "Start mining failed");
	});
	addGatewayClientOptions(mining.command("stop").description("Stop SAT mining").option("--json", "Output JSON", false)).action(async (opts) => {
		await runMiningCommand(async () => {
			renderMiningStopResult(await runMiningGatewayCommand("sat.stopMining", opts, void 0, void 0, {
				expectFinal: true,
				render: false
			}), opts);
		}, "Stop mining failed");
	});
	addGatewayClientOptions(mining.command("history").description("Show SAT mining history and activity windows").option("--window <window>", "History window (for example 24h or 7d)").option("--activity-window <window>", "Activity window override").option("--max-points <n>", "Max points to return").option("--json", "Output JSON", false)).action(async (opts) => {
		await runMiningCommand(async () => {
			await runMiningGatewayCommand("sat.getMiningHistory", opts, {
				window: typeof opts.window === "string" ? opts.window.trim() || void 0 : void 0,
				activityWindow: typeof opts.activityWindow === "string" ? opts.activityWindow.trim() || void 0 : void 0,
				maxPoints: parsePositiveInt(opts.maxPoints, "--max-points")
			});
		}, "Mining history failed");
	});
	addGatewayClientOptions(mining.command("claim-backlog").description("Claim the oldest ready SAT reward backlog batch").option("--json", "Output JSON", false)).action(async (opts) => {
		await runMiningCommand(async () => {
			await runMiningGatewayCommand("sat.claimBacklog", opts, void 0, "Claim backlog submitted");
		}, "Claim backlog failed");
	});
	addGatewayClientOptions(mining.command("keeper").description("Run permissionless SAT keeper work").command("run").description("Run one SAT keeper/cranker settlement tick").option("--once", "Run one tick and exit", true).option("--json", "Output JSON", false)).action(async (opts) => {
		await runMiningCommand(async () => {
			await runMiningGatewayCommand("sat.runKeeperOnce", opts, void 0, "Keeper tick submitted");
		}, "Keeper tick failed");
	});
	addGatewayClientOptions(mining.command("cleanup").description("Recover rent from resolved SAT accounts").command("resolved").description("Close resolved cycle accounts for a specific cycle").requiredOption("--cycle <id>", "Cycle id to clean").option("--json", "Output JSON", false)).action(async (opts) => {
		await runMiningCommand(async () => {
			await runMiningGatewayCommand("sat.closeResolvedCycleAccounts", opts, { cycleId: parsePositiveInt(opts.cycle, "--cycle") }, "Resolved cycle cleanup submitted");
		}, "Resolved cycle cleanup failed");
	});
	addGatewayClientOptions(mining.command("deposit-capital").description("Deposit SOL into SAT miner capital").option("--sol <amount>", "SOL amount to deposit").option("--lamports <amount>", "Lamports amount to deposit").option("--json", "Output JSON", false)).action(async (opts) => {
		await runMiningCommand(async () => {
			await runMiningGatewayCommand("sat.depositMinerCapital", opts, { lamports: parseLamportsInput(opts) }, "Miner capital deposited");
		}, "Deposit miner capital failed");
	});
	addGatewayClientOptions(mining.command("withdraw-capital").description("Withdraw SOL from SAT miner capital").option("--sol <amount>", "SOL amount to withdraw").option("--lamports <amount>", "Lamports amount to withdraw").option("--json", "Output JSON", false)).action(async (opts) => {
		await runMiningCommand(async () => {
			await runMiningGatewayCommand("sat.withdrawMinerCapital", opts, { lamports: parseLamportsInput(opts) }, "Miner capital withdrawn");
		}, "Withdraw miner capital failed");
	});
	addGatewayClientOptions(mining.command("set-commit").description("Set the active SAT mining commit amount").option("--sol <amount>", "SOL amount to commit").option("--lamports <amount>", "Lamports amount to commit").option("--no-persist-config", "Do not persist the commit in runtime config").option("--json", "Output JSON", false)).action(async (opts) => {
		await runMiningCommand(async () => {
			await runMiningGatewayCommand("sat.setActiveCommit", opts, {
				lamports: parseLamportsInput(opts),
				persistConfig: opts.persistConfig !== false
			}, "Mining commit updated");
		}, "Set mining commit failed");
	});
}

//#endregion
export { registerMiningCli };