import { _ as resolveStateDir } from "./paths-C9FmTW1x.js";
import { d as defaultRuntime } from "./errors-Dx3S3Nrp.js";
import { t as readManagedFederationTokenSummary } from "./federation-BrNm7xtG.js";
import { fileURLToPath } from "node:url";
import fs from "node:fs";
import path from "node:path";
import { spawn } from "node:child_process";

//#region src/managed/tunnel.ts
function readManagedReservationSummaries(env = process.env) {
	const stateDir = resolveStateDir(env);
	const entries = fs.readdirSync(stateDir, { withFileTypes: true });
	const summaries = [];
	for (const entry of entries) {
		if (!entry.isFile() || !entry.name.endsWith(".zrok-reservation")) continue;
		const filePath = path.join(stateDir, entry.name);
		try {
			const token = fs.readFileSync(filePath, "utf8").trim();
			summaries.push({
				path: filePath,
				slug: entry.name.slice(0, -17),
				tokenPresent: token.length > 0
			});
		} catch {
			summaries.push({
				path: filePath,
				slug: entry.name.slice(0, -17),
				tokenPresent: false
			});
		}
	}
	return summaries;
}

//#endregion
//#region src/commands/managed-up.ts
const MANAGED_SCRIPT_BASENAMES = ["start-managed.sh", "start-vps.sh"];
function appendManagedScriptCandidates(candidates, seen, anchorFile) {
	if (!anchorFile) return;
	const anchorDir = path.dirname(path.resolve(anchorFile));
	for (const depth of [
		0,
		1,
		2,
		3
	]) {
		const rel = Array.from({ length: depth }, () => "..");
		for (const basename of MANAGED_SCRIPT_BASENAMES) {
			const candidate = path.resolve(anchorDir, ...rel, "scripts", basename);
			if (seen.has(candidate)) continue;
			seen.add(candidate);
			candidates.push(candidate);
		}
	}
}
function resolveManagedScriptPath() {
	const candidates = [];
	const seen = /* @__PURE__ */ new Set();
	for (const basename of MANAGED_SCRIPT_BASENAMES) {
		const cwdCandidate = path.resolve(process.cwd(), "scripts", basename);
		seen.add(cwdCandidate);
		candidates.push(cwdCandidate);
	}
	appendManagedScriptCandidates(candidates, seen, process.argv[1]);
	appendManagedScriptCandidates(candidates, seen, fileURLToPath(import.meta.url));
	for (const candidate of candidates) if (fs.existsSync(candidate)) return candidate;
	throw new Error("Unable to locate scripts/start-managed.sh or scripts/start-vps.sh");
}
async function managedUpCommand(runtime = defaultRuntime, options = {}) {
	const scriptPath = resolveManagedScriptPath();
	const fed = readManagedFederationTokenSummary(process.env);
	const reservations = readManagedReservationSummaries(process.env);
	if (options.json) {
		runtime.log(JSON.stringify({
			ok: true,
			scriptPath,
			federation: fed,
			reservations
		}, null, 2));
		return;
	}
	const child = spawn("bash", [scriptPath], {
		env: {
			...process.env,
			FASED_MANAGED_INTERNAL: "1"
		},
		stdio: "inherit",
		cwd: process.cwd()
	});
	const exitCode = await new Promise((resolve, reject) => {
		child.once("error", reject);
		child.once("exit", (code, signal) => {
			if (signal) {
				reject(/* @__PURE__ */ new Error(`managed up interrupted by signal: ${signal}`));
				return;
			}
			resolve(code ?? 1);
		});
	});
	if (exitCode !== 0) throw new Error(`managed up failed (exit=${exitCode})`);
}

//#endregion
export { resolveManagedScriptPath as n, readManagedReservationSummaries as r, managedUpCommand as t };