"use strict";
/* Socket Lib - Built with rolldown */
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
const require_runtime = require('../_virtual/_rolldown/runtime.js');
const require_primordials_error = require('../primordials/error.js');
const require_primordials_array = require('../primordials/array.js');
const require_primordials_map_set = require('../primordials/map-set.js');
const require_primordials_object = require('../primordials/object.js');
const require_primordials_json = require('../primordials/json.js');
const require_errors_message = require('../errors/message.js');
const require_logger_default = require('../logger/default.js');
const require_argv_parse = require('../argv/parse.js');
const require_checks_primordials_defaults = require('../checks/primordials-defaults.js');
const require_checks_primordials = require('../checks/primordials.js');
let node_fs = require("node:fs");
let node_path = require("node:path");
node_path = require_runtime.__toESM(node_path);
let node_process = require("node:process");
node_process = require_runtime.__toESM(node_process);

//#region src/bin/check-primordials.ts
/**
* @file `socket-lib check primordials` handler. Loads a JSON config from disk
*   (default `primordials-coverage.config.json` at the repo root, override with
*   `--config <path>`), runs the drift check, and renders the result.
*   socket-lib check primordials socket-lib check primordials --config
*   ./primordials.config.json socket-lib check primordials --json #
*   machine-readable output socket-lib check primordials --explain # one
*   detailed line per finding socket-lib check primordials --silent # silent on
*   success Exit codes: 0 — no drift 1 — drift detected (or config / lookup
*   error)
*/
const logger = require_logger_default.getDefaultLogger();
const DEFAULT_CONFIG_PATH = ".socket-lib.json";
const FALLBACK_CONFIG_PATHS = [".socket-lib.json", ".config/socket-lib.json"];
const CONFIG_SECTION = "primordials";
function parseArgs(argv) {
	const { values } = require_argv_parse.parseArgs({
		args: argv,
		strict: false,
		options: {
			config: {
				type: "string",
				short: "c"
			},
			explain: { type: "boolean" },
			help: {
				type: "boolean",
				short: "h"
			},
			json: { type: "boolean" },
			silent: { type: "boolean" }
		}
	});
	const explicitConfig = values["config"];
	return {
		config: typeof explicitConfig === "string" ? explicitConfig : void 0,
		json: Boolean(values["json"]),
		explain: Boolean(values["explain"]),
		silent: Boolean(values["silent"]),
		help: Boolean(values["help"])
	};
}
/**
* Pick the config file. Returns the explicit `--config` argument when given
* (even if it doesn't exist — the caller will surface the error with the path
* they typed). Otherwise probes the fallback list in order and returns the
* first hit. Returns the head of the list when none exist, so the caller's
* "config file not found" error message names the canonical default.
*/
function resolveConfigPath(explicit) {
	if (explicit !== void 0) return explicit;
	for (const candidate of FALLBACK_CONFIG_PATHS) if ((0, node_fs.existsSync)(node_path.default.resolve(candidate))) return candidate;
	return FALLBACK_CONFIG_PATHS[0];
}
function printHelp() {
	logger.log("socket-lib check primordials — primordials drift check");
	logger.log("");
	logger.log("Usage:");
	logger.log("  socket-lib check primordials [opts]");
	logger.log("  socket-lib check prim        [opts]    # short alias");
	logger.log("");
	logger.log("Options:");
	logger.log(`  --config, -c <path>   Config file. Default: ${DEFAULT_CONFIG_PATH}`);
	logger.log(`                        (falls back to .config/socket-lib.json)`);
	logger.log("  --explain             Print one detailed line per finding.");
	logger.log("  --json                Machine-readable JSON output.");
	logger.log("  --silent              Silent on success.");
	logger.log("  --help, -h            Print this help.");
	logger.log("");
	logger.log("Config (.socket-lib.json — primordials section):");
	logger.log("  {");
	logger.log("    \"primordials\": {");
	logger.log("      \"scanDirs\":         [\"src\", \"additions/source-patched/lib\"]");
	logger.log("    }");
	logger.log("  }");
	logger.log("");
	logger.log("Only `scanDirs` is required. `aliasMap` and `nodeInternalOnly`");
	logger.log("default to the fleet-canonical sets and only need entries when");
	logger.log("your repo extends or overrides them.");
	logger.log("");
	logger.log("A bare object (no `primordials` section) is also accepted for");
	logger.log("repos that only run this one check.");
}
function loadConfig(configPath) {
	if (!(0, node_fs.existsSync)(configPath)) throw new require_primordials_error.ErrorCtor(`config file not found: ${configPath}`);
	let parsed;
	try {
		parsed = require_primordials_json.JSONParse((0, node_fs.readFileSync)(configPath, "utf8"));
	} catch (e) {
		throw new require_primordials_error.ErrorCtor(`config file is not valid JSON: ${require_errors_message.errorMessage(e)}`);
	}
	if (typeof parsed !== "object" || parsed === null || require_primordials_array.ArrayIsArray(parsed)) throw new require_primordials_error.ErrorCtor("config root must be an object");
	const root = parsed;
	const sectional = root[CONFIG_SECTION];
	const raw = sectional !== void 0 ? sectional : root;
	if (!require_primordials_array.ArrayIsArray(raw.scanDirs)) throw new require_primordials_error.ErrorCtor(`config.scanDirs must be an array of strings (got ${typeof raw.scanDirs})`);
	for (const [i, v] of raw.scanDirs.entries()) if (typeof v !== "string") throw new require_primordials_error.ErrorCtor(`config.scanDirs[${i}] must be a string`);
	if (raw.aliasMap !== void 0 && (typeof raw.aliasMap !== "object" || raw.aliasMap === null || require_primordials_array.ArrayIsArray(raw.aliasMap))) throw new require_primordials_error.ErrorCtor("config.aliasMap must be an object of source→target");
	if (raw.nodeInternalOnly !== void 0 && !require_primordials_array.ArrayIsArray(raw.nodeInternalOnly)) throw new require_primordials_error.ErrorCtor("config.nodeInternalOnly must be an array of strings");
	const aliasMap = new require_primordials_map_set.MapCtor([...require_primordials_object.ObjectEntries(require_checks_primordials_defaults.DEFAULT_ALIAS_MAP), ...require_primordials_object.ObjectEntries(raw.aliasMap ?? {})]);
	const nodeInternalOnly = new require_primordials_map_set.SetCtor([...require_checks_primordials_defaults.DEFAULT_NODE_INTERNAL_ONLY, ...(raw.nodeInternalOnly ?? []).filter((x) => typeof x === "string")]);
	return {
		scanDirs: raw.scanDirs,
		aliasMap,
		nodeInternalOnly,
		socketLibPrimordialsPath: typeof raw.socketLibPrimordialsPath === "string" ? raw.socketLibPrimordialsPath : void 0,
		repoRoot: node_process.default.cwd()
	};
}
function serialize(result) {
	return {
		ok: result.findings.length === 0,
		used: result.used.size,
		findings: result.findings.map((f) => ({
			kind: f.kind,
			name: f.name,
			files: f.files,
			hint: f.hint
		}))
	};
}
function renderHuman(result, args) {
	if (result.findings.length === 0) {
		if (!args.silent) logger.success(`Primordials coverage OK — ${result.used.size} names used, all accounted for.`);
		return;
	}
	logger.error(`Primordials drift detected — ${result.findings.length} unaccounted name(s):`);
	for (const f of result.findings) {
		logger.error(`  ${f.name}`);
		if (args.explain) {
			logger.error(`    ${f.hint}`);
			if (f.files.length > 0) logger.error(`    files: ${f.files.join(", ")}`);
		}
	}
	if (!args.explain) {
		logger.error("");
		logger.error("Run with --explain for fix instructions and file references.");
	}
}
async function runCheckPrimordials(argv) {
	const args = parseArgs(argv);
	if (args.help) {
		printHelp();
		return 0;
	}
	let config;
	try {
		config = loadConfig(node_path.default.resolve(resolveConfigPath(args.config)));
	} catch (e) {
		logger.error(`socket-lib check primordials: ${require_errors_message.errorMessage(e)}`);
		return 1;
	}
	let result;
	try {
		result = require_checks_primordials.checkPrimordials(config);
	} catch (e) {
		logger.error(`socket-lib check primordials: ${require_errors_message.errorMessage(e)}`);
		return 1;
	}
	if (args.json) logger.log(require_primordials_json.JSONStringify(serialize(result), null, 2));
	else renderHuman(result, args);
	return result.findings.length === 0 ? 0 : 1;
}

//#endregion
exports.loadConfig = loadConfig;
exports.parseArgs = parseArgs;
exports.printHelp = printHelp;
exports.renderHuman = renderHuman;
exports.resolveConfigPath = resolveConfigPath;
exports.runCheckPrimordials = runCheckPrimordials;
exports.serialize = serialize;