import { u as restartData } from "./scripts-DRNH_1sI.mjs";
import { charNotIn, createRegExp, exactly, oneOrMore } from "magic-regexp";
import path from "path";
import fs from "node:fs";
import consola, { consola as consola$1 } from "consola";
import { execSync } from "node:child_process";
import { readFile, unlink, writeFile } from "node:fs/promises";
import path$1 from "node:path";
import { pipeline } from "node:stream/promises";
import os from "node:os";
import * as tar from "tar";
import extractZip from "extract-zip";

//#region src/utils/mmdbctlInstaller.ts
const VERSION = "1.4.8";
const LOCAL_BIN_DIR = path$1.join(os.homedir(), ".shield-base", "bin");
function getTargetPlatform() {
	const platform = os.platform();
	const arch = os.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 = path$1.join(LOCAL_BIN_DIR, binaryName);
	try {
		execSync("mmdbctl --help", { stdio: "ignore" });
		return "mmdbctl";
	} catch {
		if (process.env.CI === "true" || !process.stdout.isTTY) throw new Error("mmdbctl not found in PATH. Please ensure it is installed in your CI environment");
	}
	if (fs.existsSync(localBinaryPath)) return localBinaryPath;
	consola$1.warn("The required engine \"mmdbctl\" is missing from your system.");
	if (!await consola$1.prompt("Would you like to automatically download and configure it locally?", {
		type: "confirm",
		initial: true
	})) {
		consola$1.error("Cannot proceed without mmdbctl. Exiting...");
		process.exit(1);
	}
	fs.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 = path$1.join(LOCAL_BIN_DIR, `${fileName}${ext}`);
	consola$1.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 = fs.createWriteStream(archivePath);
		await pipeline(response.body, fileStream);
		consola$1.success("Download complete. Extracting...");
		if (isWindows) await extractZip(archivePath, { dir: LOCAL_BIN_DIR });
		else await tar.x({
			file: archivePath,
			cwd: LOCAL_BIN_DIR
		});
		const extractedBinary = fs.readdirSync(LOCAL_BIN_DIR).find((f) => f.includes("mmdbctl") && f !== `${fileName}${ext}`);
		if (extractedBinary && extractedBinary !== binaryName) fs.renameSync(path$1.join(LOCAL_BIN_DIR, extractedBinary), localBinaryPath);
		fs.unlinkSync(archivePath);
		if (!isWindows) fs.chmodSync(localBinaryPath, 493);
		consola$1.success("mmdbctl engine successfully installed locally!");
		return localBinaryPath;
	} catch (error) {
		consola$1.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 = charNotIn(" ");
	const nonAtOrSpace = charNotIn(" @");
	const emailPart = oneOrMore(nonAtOrSpace).and("@").and(oneOrMore(nonAtOrSpace)).and(".").and(oneOrMore(nonAtOrSpace));
	if (createRegExp(oneOrMore(nonSpace).and(oneOrMore(exactly(" ").and(oneOrMore(nonSpace))).optionally()).and(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.prompt(message, {
			type: "text",
			placeholder: "acmeco bgp.tools - contact@acme.co",
			cancel: "null"
		});
		if (input === null) {
			consola.fail("Operation cancelled. Exiting Shield-Base...");
			process.exit(1);
		}
		contactInfo = input;
		const validationResult = isValidUserAgent(contactInfo);
		if (validationResult === true) isValid = true;
		else consola.error(validationResult);
	}
	return contactInfo;
}

//#endregion
//#region src/scripts/_internal.ts
function __cache() {
	const _cacheOutput = path.join(os.homedir(), ".shield-base", ".cache.json");
	const _cacheDir = path.dirname(_cacheOutput);
	const _getCache = async () => {
		if (fs.existsSync(_cacheOutput)) try {
			const cachedFile = await readFile(_cacheOutput, "utf-8");
			return JSON.parse(cachedFile);
		} catch (err) {
			console.error(`Error reading cache`, err);
		}
	};
	const _setCache = async (_data) => {
		if (!fs.existsSync(_cacheDir)) fs.mkdirSync(_cacheDir, { recursive: true });
		try {
			await writeFile(_cacheOutput, JSON.stringify(_data, null, 2), "utf-8");
		} catch (err) {
			console.error(`Error setting cache`, err);
		}
	};
	const _deleteCache = async (_dataToDelete, all) => {
		if (all) {
			if (fs.existsSync(_cacheOutput)) try {
				await unlink(_cacheOutput);
			} catch (err) {
				console.error(`Error deleting cache`, err);
			}
			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)));
		try {
			await writeFile(_cacheOutput, JSON.stringify(updated, null, 2), "utf-8");
		} catch (err) {
			console.error(`Error updating cache`, err);
		}
	};
	return {
		_getCache,
		_setCache,
		_deleteCache,
		_cacheOutput,
		_cacheDir
	};
}

//#endregion
export { askForUserAgent as __askForUserAgent, __cache, ensureMmdbctl as __ensureMmdbctl, restartData as __restartData };
//# sourceMappingURL=_internal.mjs.map