import { parseSessionKey } from "../services/channel-sender.mjs";
import { isFlyControlAvailable, restartAllMachines } from "../services/fly-control-service.mjs";
import { getCurrentCommit, performUpdate } from "../services/update-service.mjs";
//#region extensions/crypto/src/commands/update-command.ts
/**
* /update + /restart — Update and restart the bot from Telegram.
*
* /update  — Clone latest, build, install, restart. Verbose progress.
* /restart — Just restart the Fly machine (no code update).
*
* Both commands send live progress messages to the user's chat via
* the channel sender so they can see each step happening.
*
* Requires: FLY_API_TOKEN (already used by /flykeys, /flystatus, etc.)
*/
let _sender = null;
function setUpdateCommandSender(sender) {
	_sender = sender;
}
const updateCommand = {
	name: "update",
	description: "Update to latest OpenClawnch and restart",
	acceptsArgs: false,
	requireAuth: true,
	handler: async (ctx) => {
		const sessionKey = ctx?.sessionKey ?? "";
		const chatId = ctx?.conversationId ?? ctx?.senderId ?? "";
		const channel = (sessionKey ? parseSessionKey(sessionKey) : null)?.channel ?? "telegram";
		const progress = async (msg) => {
			if (_sender && chatId) try {
				await _sender.send(channel, String(chatId), msg);
			} catch {}
		};
		if (!isFlyControlAvailable()) return { text: "Fly.io not configured — /update requires FLY_API_TOKEN.\n\nSet it up:\n```\nfly secrets set FLY_API_TOKEN=\"$(fly tokens create deploy -a <app>)\" -a <app>\n```" };
		await progress(`Starting update...\nCurrent: ${getCurrentCommit() ?? "unknown"}\nThis will take 1-2 minutes. You'll see progress below.`);
		const result = await performUpdate(progress);
		if (result.success) return { text: `Update complete.\n${result.message}\n\nBot is restarting — back in ~30s.` };
		return { text: `Update failed.\n\n${result.message}` };
	}
};
const restartCommand = {
	name: "restart",
	description: "Restart the bot (no code update, just restart the machine)",
	acceptsArgs: false,
	requireAuth: true,
	handler: async (ctx) => {
		if (!isFlyControlAvailable()) return { text: "Fly.io not configured — /restart requires FLY_API_TOKEN.\n\nSet it up:\n```\nfly secrets set FLY_API_TOKEN=\"$(fly tokens create deploy -a <app>)\" -a <app>\n```" };
		const sessionKey = ctx?.sessionKey ?? "";
		const chatId = ctx?.conversationId ?? ctx?.senderId ?? "";
		const channel = (sessionKey ? parseSessionKey(sessionKey) : null)?.channel ?? "telegram";
		if (_sender && chatId) try {
			await _sender.send(channel, String(chatId), "Restarting machine...");
		} catch {}
		try {
			return { text: `Restarting ${(await restartAllMachines()).length} machine(s). Back in ~30s.` };
		} catch (err) {
			return { text: `Restart failed: ${err instanceof Error ? err.message : String(err)}` };
		}
	}
};
//#endregion
export { restartCommand, setUpdateCommandSender, updateCommand };

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