import { createLogger } from "../utils/logger/index.js";
import { init_logger } from "../utils/logger.js";
import { spawn } from "node:child_process";
//#region src/tunnel/frpc-process.ts
init_logger();
const log = createLogger("TunnelFrpc");
const LOGIN_SUCCESS_RE = /login to server success/i;
const RECONNECT_SUCCESS_RE = /reconnect success/i;
function spawnFrpcProcess(frpcBin, configPath) {
	const child = spawn(frpcBin, ["-c", configPath], { stdio: [
		"ignore",
		"pipe",
		"pipe"
	] });
	let loginResolve;
	let loginReject;
	const waitForLoginSuccess = new Promise((resolve, reject) => {
		loginResolve = resolve;
		loginReject = reject;
		setTimeout(() => reject(/* @__PURE__ */ new Error("frpc login timeout")), 6e4);
	});
	const exitHandlers = [];
	const onLine = (line) => {
		if (LOGIN_SUCCESS_RE.test(line) || RECONNECT_SUCCESS_RE.test(line)) {
			loginResolve?.();
			loginResolve = void 0;
			loginReject = void 0;
		}
	};
	child.stdout?.on("data", (chunk) => {
		for (const line of chunk.toString("utf8").split("\n")) {
			if (line.trim()) log.debug({ line: line.trim() }, "frpc stdout");
			onLine(line);
		}
	});
	child.stderr?.on("data", (chunk) => {
		for (const line of chunk.toString("utf8").split("\n")) {
			if (line.trim()) log.debug({ line: line.trim() }, "frpc stderr");
			onLine(line);
		}
	});
	child.on("error", (err) => {
		loginReject?.(err);
		loginResolve = void 0;
		loginReject = void 0;
	});
	child.on("exit", (code, signal) => {
		for (const h of exitHandlers) h(code, signal);
	});
	if (!child.pid) throw new Error("Failed to spawn frpc process");
	return {
		pid: child.pid,
		waitForLoginSuccess,
		onExit: (handler) => {
			exitHandlers.push(handler);
		},
		kill: async (signal = "SIGTERM") => {
			if (!child.pid || child.killed) return;
			child.kill(signal);
			await new Promise((resolve) => {
				const t = setTimeout(() => {
					if (!child.killed) child.kill("SIGKILL");
					resolve();
				}, 3e3);
				child.once("exit", () => {
					clearTimeout(t);
					resolve();
				});
			});
		}
	};
}
//#endregion
export { spawnFrpcProcess };

//# sourceMappingURL=frpc-process.js.map