Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
const require_scripts = require('./scripts-DAvbaBhI.cjs');
let magic_regexp = require("magic-regexp");
let path = require("path");
path = require_scripts.__toESM(path);
let node_fs = require("node:fs");
node_fs = require_scripts.__toESM(node_fs);
let consola = require("consola");
consola = require_scripts.__toESM(consola);
let node_child_process = require("node:child_process");
let node_fs_promises = require("node:fs/promises");
let node_path = require("node:path");
node_path = require_scripts.__toESM(node_path);
let node_stream_promises = require("node:stream/promises");
let node_os = require("node:os");
node_os = require_scripts.__toESM(node_os);
let tar = require("tar");
tar = require_scripts.__toESM(tar);
let extract_zip = require("extract-zip");
extract_zip = require_scripts.__toESM(extract_zip);

//#region src/utils/mmdbctlInstaller.ts
const VERSION = "1.4.8";
const LOCAL_BIN_DIR = node_path.default.join(node_os.default.homedir(), ".shield-base", "bin");
function getTargetPlatform() {
	const platform = node_os.default.platform();
	const arch = node_os.default.arch();
	let osName = "";
	let archName = "";
	let ext = ".tar.gz";
	let isWindows = false;
	if (platform === "darwin") osName = "darwin";
	else if (platform === "linux") osName = "linux";
	else if (platform === "win32") {
		osName = "windows";
		ext = ".zip";
		isWindows = true;
	} else throw new Error(`Unsupported OS: ${platform}`);
	if (arch === "x64") archName = "amd64";
	else if (arch === "arm64") archName = "arm64";
	else if (arch === "ia32") archName = "386";
	else if (arch === "arm") archName = "arm";
	else throw new Error(`Unsupported Architecture: ${arch}`);
	return {
		plat: `${osName}_${archName}`,
		ext,
		isWindows
	};
}
async function ensureMmdbctl() {
	const { plat, ext, isWindows } = getTargetPlatform();
	const binaryName = isWindows ? "mmdbctl.exe" : "mmdbctl";
	const localBinaryPath = node_path.default.join(LOCAL_BIN_DIR, binaryName);
	try {
		(0, node_child_process.execSync)("mmdbctl --help", { stdio: "ignore" });
		return "mmdbctl";
	} catch {}
	if (node_fs.default.existsSync(localBinaryPath)) return localBinaryPath;
	consola.consola.warn("The required engine \"mmdbctl\" is missing from your system.");
	if (!await consola.consola.prompt("Would you like to automatically download and configure it locally?", {
		type: "confirm",
		initial: true
	})) {
		consola.consola.error("Cannot proceed without mmdbctl. Exiting...");
		process.exit(1);
	}
	node_fs.default.mkdirSync(LOCAL_BIN_DIR, { recursive: true });
	const fileName = `mmdbctl_${VERSION}_${plat}`;
	const url = `https://github.com/ipinfo/mmdbctl/releases/download/mmdbctl-${VERSION}/${fileName}${ext}`;
	const archivePath = node_path.default.join(LOCAL_BIN_DIR, `${fileName}${ext}`);
	consola.consola.start(`Downloading mmdbctl v${VERSION} for ${plat}...`);
	try {
		const response = await fetch(url);
		if (!response.ok || !response.body) throw new Error(`Failed to fetch: ${response.statusText}`);
		const fileStream = node_fs.default.createWriteStream(archivePath);
		await (0, node_stream_promises.pipeline)(response.body, fileStream);
		consola.consola.success("Download complete. Extracting...");
		if (isWindows) await (0, extract_zip.default)(archivePath, { dir: LOCAL_BIN_DIR });
		else await tar.x({
			file: archivePath,
			cwd: LOCAL_BIN_DIR
		});
		const extractedBinary = node_fs.default.readdirSync(LOCAL_BIN_DIR).find((f) => f.includes("mmdbctl") && f !== `${fileName}${ext}`);
		if (extractedBinary && extractedBinary !== binaryName) node_fs.default.renameSync(node_path.default.join(LOCAL_BIN_DIR, extractedBinary), localBinaryPath);
		node_fs.default.unlinkSync(archivePath);
		if (!isWindows) node_fs.default.chmodSync(localBinaryPath, 493);
		consola.consola.success("mmdbctl engine successfully installed locally!");
		return localBinaryPath;
	} catch (error) {
		consola.consola.error("Failed to install mmdbctl automatically:", error);
		process.exit(1);
	}
}

//#endregion
//#region src/utils/validateUserAgent.ts
function isValidUserAgent(ua) {
	if (!ua || ua.trim() === "") return "User agent is required";
	const nonSpace = (0, magic_regexp.charNotIn)(" ");
	const nonAtOrSpace = (0, magic_regexp.charNotIn)(" @");
	const emailPart = (0, magic_regexp.oneOrMore)(nonAtOrSpace).and("@").and((0, magic_regexp.oneOrMore)(nonAtOrSpace)).and(".").and((0, magic_regexp.oneOrMore)(nonAtOrSpace));
	if ((0, magic_regexp.createRegExp)((0, magic_regexp.oneOrMore)(nonSpace).and((0, magic_regexp.oneOrMore)((0, magic_regexp.exactly)(" ").and((0, magic_regexp.oneOrMore)(nonSpace))).optionally()).and((0, magic_regexp.exactly)(" - ")).and(emailPart).at.lineStart().at.lineEnd()).test(ua)) return true;
	return "Invalid format. Expected: '<name> [url] - <email>' (e.g., 'acmeco bgp.tools - contact@acme.co')";
}

//#endregion
//#region src/utils/userAgentInput.ts
async function askForUserAgent() {
	const message = [
		"bgp.tools requires your contact information as one of the data sources.",
		"It will be sent as a User-Agent header on every request to their API.",
		`More info: https://bgp.tools/kb/api`,
		"",
		"Format: <name or company> [site url] - <email>"
	].join("\n");
	let contactInfo = "";
	let isValid = false;
	while (!isValid) {
		const input = await consola.default.prompt(message, {
			type: "text",
			placeholder: "acmeco bgp.tools - contact@acme.co",
			cancel: "null"
		});
		if (input === null) {
			consola.default.fail("Operation cancelled. Exiting Shield-Base...");
			process.exit(1);
		}
		contactInfo = input;
		const validationResult = isValidUserAgent(contactInfo);
		if (validationResult === true) isValid = true;
		else consola.default.error(validationResult);
	}
	return contactInfo;
}

//#endregion
//#region src/scripts/_internal.ts
function __cache() {
	const _cacheOutput = path.default.join(node_os.default.homedir(), ".shield-base", ".cache.json");
	const _cacheDir = path.default.dirname(_cacheOutput);
	const _getCache = async () => {
		const cachedFile = await (0, node_fs_promises.readFile)(_cacheOutput, "utf-8");
		return await JSON.parse(cachedFile);
	};
	const _setCache = async (_data) => {
		if (!node_fs.default.existsSync(_cacheDir)) node_fs.default.mkdirSync(_cacheDir, { recursive: true });
		await (0, node_fs_promises.writeFile)(_cacheOutput, JSON.stringify(_data, null, 2), "utf-8");
	};
	const _deleteCache = async (_dataToDelete, all) => {
		if (all) {
			await (0, node_fs_promises.unlink)(_cacheOutput);
			return;
		}
		const current = await _getCache();
		if (!current) return;
		const keysToDelete = new Set(Object.keys(_dataToDelete));
		const updated = Object.fromEntries(Object.entries(current).filter(([k]) => !keysToDelete.has(k)));
		await (0, node_fs_promises.writeFile)(_cacheOutput, JSON.stringify(updated, null, 2), "utf-8");
	};
	return {
		_getCache,
		_setCache,
		_deleteCache,
		_cacheOutput,
		_cacheDir
	};
}

//#endregion
exports.__askForUserAgent = askForUserAgent;
exports.__cache = __cache;
exports.__ensureMmdbctl = ensureMmdbctl;
exports.__restartData = require_scripts.restartData;
//# sourceMappingURL=_internal.cjs.map