import { spawnSync } from "node:child_process";
import * as fs from "node:fs";
import * as path from "node:path";
import type { ExternalProcessStatus, HerdrCoreLocalMachineReference, HerdrLocalMachineReference, HerdrMachineReference, PlacementMachineReference } from "../../shared/types.ts";
import { getAgentDir, getProjectConfigDir } from "../../shared/utils.ts";
import { CODE_OWNED_EXTERNAL_CLI_ADAPTER_IDS } from "./external-cli-contract.ts";
import type { runExternalCli } from "./external-cli-runner.ts";
import { herdrLocalEnv, parseHerdrEndpoint } from "./herdr-connection.ts";
import { REX_LOCAL_MACHINE, resolveLocalLaunchCwd, resolveRexLocalPlacement } from "./rex-machine.ts";
export { shellQuoteRemote as shellQuote } from "./herdr-connection.ts";

/**
 * Herdr saved-machine placement for external CLI children.
 *
 * Herdr owns which machines exist and how ssh reaches them (`herdr machine list --json`).
 * pi-subagents owns what runs there: native Pi and the six code-owned external profiles are
 * launched in fresh Herdr-owned visible panes. SSH is bounded transport and never owns the agent.
 * `cwd` means the directory on that machine; the remote `cd` is the directory check.
 */

const MAX_MACHINE_NAME_LENGTH = 128;
const HERDR_MACHINE_LIST_TIMEOUT_MS = 7_500;
const MAX_HERDR_MACHINE_LIST_BYTES = 1024 * 1024;
const CONTROL_CHARS = /[\u0000-\u001f\u007f]/u;
const SUPPORTED_MACHINE_ADAPTERS = new Set<string>(CODE_OWNED_EXTERNAL_CLI_ADAPTER_IDS);

type RunExternalCliInput = Parameters<typeof runExternalCli>[0];

interface HerdrMachineCatalogEntry {
	id: string;
	label?: string;
	target: string;
	session?: string;
	enabled: boolean;
}

interface MachineSettingsEntry {
	cwd?: string;
	env?: Record<string, string>;
	/** User settings only: run this machine's children in Rex panes reached over SSH at `ssh`. */
	rex?: { ssh: string };
}

export interface ResolveHerdrMachinePlacementInput {
	/** Profile id or label as typed by the operator. */
	machine: string;
	/** Local directory whose project settings hold `subagents.machines`. */
	cwd: string;
	/** Launch cwd: absolute or `~` paths are remote paths as given; relative paths join the configured machine root. */
	stepCwd?: string;
	env?: NodeJS.ProcessEnv;
	/** Test seam: catalog JSON instead of spawning `herdr machine list --json`. */
	catalogJson?: string;
	/** Test seam: settings entry instead of reading settings files. */
	settings?: MachineSettingsEntry;
	herdrBin?: string;
	hcBin?: string;
}

export interface HerdrMachinePlacement extends MachinePlacement { machine: HerdrMachineReference }

/** A resolved `machine` value: a Herdr saved machine, a Rex SSH host, or the reserved `local` (a child of the Herdr, Herdr Core or Rex terminal this Pi runs in). */
export interface MachinePlacement {
	machine: PlacementMachineReference;
	/** Opt-in `subagents.machines.<name>.env`, exported in front of the remote command. */
	env?: Record<string, string>;
}

export interface PreparedHerdrMachineExternalCliRun {
	input: RunExternalCliInput;
	decorateProcess(process: ExternalProcessStatus): ExternalProcessStatus;
}

function validateMachineName(value: string): string {
	const trimmed = value.trim();
	if (!trimmed) throw new Error("Herdr machine id or label is required.");
	if (trimmed.length > MAX_MACHINE_NAME_LENGTH) throw new Error(`Herdr machine '${trimmed.slice(0, 24)}…' exceeds ${MAX_MACHINE_NAME_LENGTH} characters.`);
	if (CONTROL_CHARS.test(trimmed)) throw new Error("Herdr machine id or label contains control characters.");
	return trimmed;
}

function validateTarget(value: string, requested: string): string {
	const target = value.trim();
	if (!target || target.startsWith("-") || /[\s\u0000-\u001f\u007f]/u.test(target)) {
		throw new Error(`Herdr machine '${requested}' has an ssh target that cannot be passed safely: ${JSON.stringify(target)}.`);
	}
	return target;
}

function isRemoteAbsolute(value: string): boolean {
	return value.startsWith("/") || value === "~" || value.startsWith("~/");
}

function validateRemoteCwd(value: string, requested: string): string {
	const cwd = value.trim();
	if (!isRemoteAbsolute(cwd)) throw new Error(`Herdr machine '${requested}' cwd must be an absolute POSIX path or start with '~': ${JSON.stringify(cwd)}.`);
	if (CONTROL_CHARS.test(cwd)) throw new Error(`Herdr machine '${requested}' cwd contains control characters.`);
	return cwd.length > 1 ? cwd.replace(/\/+$/u, "") : cwd;
}

function parseMachineCatalog(json: string): HerdrMachineCatalogEntry[] {
	let parsed: unknown;
	try {
		parsed = JSON.parse(json) as unknown;
	} catch (error) {
		throw new Error(`Failed to parse herdr machine list --json: ${error instanceof Error ? error.message : String(error)}`);
	}
	const entries = Array.isArray(parsed) ? parsed : (parsed && typeof parsed === "object" && Array.isArray((parsed as Record<string, unknown>).machines) ? (parsed as Record<string, unknown[]>).machines : undefined);
	if (!entries) throw new Error("herdr machine list --json returned no machine list.");
	return entries.flatMap((entry) => {
		if (!entry || typeof entry !== "object" || Array.isArray(entry)) return [];
		const record = entry as Record<string, unknown>;
		if (typeof record.id !== "string" || !record.id.trim() || typeof record.target !== "string") return [];
		return [{
			id: record.id.trim(),
			...(typeof record.label === "string" && record.label.trim() ? { label: record.label.trim() } : {}),
			target: record.target,
			...(typeof record.session === "string" && record.session.trim() ? { session: record.session.trim() } : {}),
			enabled: record.enabled !== false,
		}];
	});
}

function readHerdrMachineCatalog(env: NodeJS.ProcessEnv, herdrBin: string): HerdrMachineCatalogEntry[] {
	return parseMachineCatalog(runLocalHerdr(herdrBin, ["machine", "list", "--json"], env, `Herdr CLI '${herdrBin}' was not found on PATH. Saved-machine placement needs Herdr installed locally.`));
}

function runLocalHerdr(bin: string, args: string[], env: NodeJS.ProcessEnv, notFound: string): string {
	const result = spawnSync(bin, args, { env, encoding: "utf-8", maxBuffer: MAX_HERDR_MACHINE_LIST_BYTES, timeout: HERDR_MACHINE_LIST_TIMEOUT_MS, windowsHide: true });
	if (result.error) throw new Error((result.error as NodeJS.ErrnoException).code === "ENOENT" ? notFound : `Failed to run herdr ${args.join(" ")}: ${result.error.message}`, { cause: result.error });
	if (result.status !== 0) throw new Error(`herdr ${args.join(" ")} exited with code ${result.status}: ${(result.stderr || result.stdout).trim().slice(0, 512)}`);
	return result.stdout;
}

/** Mirrors Herdr's own selector rules: profile id first, then a unique case-sensitive label; disabled fails closed. */
function selectMachine(catalog: HerdrMachineCatalogEntry[], requested: string): HerdrMachineCatalogEntry {
	const byId = catalog.find((entry) => entry.id === requested);
	const matches = byId ? [byId] : catalog.filter((entry) => entry.label === requested);
	if (matches.length > 1) throw new Error(`Machine label '${requested}' is ambiguous; use its profile ID.`);
	const machine = matches[0];
	if (!machine) {
		const saved = catalog.filter((entry) => entry.enabled).map((entry) => entry.label ?? entry.id);
		throw new Error(`Herdr machine '${requested}' was not found. Saved machines: ${saved.length ? saved.join(", ") : "none"}. Add one with herdr machine add <target> --label <name>.`);
	}
	if (!machine.enabled) throw new Error(`Machine '${requested}' is disabled. Run herdr machine enable ${machine.id}.`);
	return machine;
}

function readJsonObject(filePath: string): Record<string, unknown> {
	if (!fs.existsSync(filePath)) return {};
	let parsed: unknown;
	try {
		parsed = JSON.parse(fs.readFileSync(filePath, "utf-8")) as unknown;
	} catch (error) {
		throw new Error(`Failed to read settings file '${filePath}': ${error instanceof Error ? error.message : String(error)}`);
	}
	return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed as Record<string, unknown> : {};
}

function machineSettingsFrom(settings: Record<string, unknown>, keys: readonly string[], filePath: string): MachineSettingsEntry | undefined {
	const subagents = settings.subagents;
	if (!subagents || typeof subagents !== "object" || Array.isArray(subagents)) return undefined;
	const machines = (subagents as Record<string, unknown>).machines;
	if (machines === undefined) return undefined;
	if (!machines || typeof machines !== "object" || Array.isArray(machines)) throw new Error(`Subagent settings in '${filePath}' have invalid 'machines'; expected an object keyed by machine label or id.`);
	const key = keys.find((candidate) => candidate in (machines as Record<string, unknown>));
	if (key === undefined) return undefined;
	const value = (machines as Record<string, unknown>)[key];
	if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`Subagent settings in '${filePath}' have invalid 'machines.${key}'; expected an object with 'cwd' and optional 'env'.`);
	const record = value as Record<string, unknown>;
	const entry: MachineSettingsEntry = {};
	if (record.cwd !== undefined) {
		if (typeof record.cwd !== "string" || !record.cwd.trim()) throw new Error(`Subagent settings in '${filePath}' have invalid 'machines.${key}.cwd'; expected a non-empty string.`);
		entry.cwd = validateRemoteCwd(record.cwd, key);
	}
	if (record.env !== undefined) {
		if (!record.env || typeof record.env !== "object" || Array.isArray(record.env) || Object.entries(record.env).some(([name, item]) => !/^[A-Za-z_][A-Za-z0-9_]*$/u.test(name) || typeof item !== "string")) {
			throw new Error(`Subagent settings in '${filePath}' have invalid 'machines.${key}.env'; expected an object of string values keyed by variable name.`);
		}
		entry.env = { ...(record.env as Record<string, string>) };
		if (Object.keys(entry.env).length > 0) {
			throw new Error(`Subagent settings in '${filePath}' set 'machines.${key}.env'. Saved-machine runs use the remote Herdr/Pi environment; configure credentials and environment on '${key}' and remove the local env map.`);
		}
	}
	if (record.rex !== undefined) {
		const rex = record.rex, ssh = rex && typeof rex === "object" && !Array.isArray(rex) && Object.keys(rex).every((field) => field === "ssh") ? (rex as Record<string, unknown>).ssh : undefined;
		if (typeof ssh !== "string") throw new Error(`Subagent settings in '${filePath}' have invalid 'machines.${key}.rex'; expected { "ssh": "<ssh target>" }.`);
		entry.rex = { ssh: validateTarget(ssh, key) };
	}
	return entry;
}

/** Project settings beat user settings, field by field; the entry may be keyed by label, id, or the typed selector. Only user settings may name a Rex SSH host, so a cloned repo never chooses where a task runs. */
function readMachineSettings(cwd: string, keys: readonly string[]): MachineSettingsEntry | undefined {
	const userPath = path.join(getAgentDir(), "settings.json");
	const projectPath = path.join(getProjectConfigDir(findProjectRootForSettings(cwd)), "settings.json");
	const user = machineSettingsFrom(readJsonObject(userPath), keys, userPath);
	const project = projectPath === userPath ? undefined : machineSettingsFrom(readJsonObject(projectPath), keys, projectPath);
	if (project?.rex) throw new Error(`Project settings '${projectPath}' set a Rex SSH host in 'machines'. Move the rex entry to your user settings '${userPath}'; only user settings choose which host a task runs on.`);
	if (!user && !project) return undefined;
	return { ...user, ...project };
}

/** Whether user settings name `machine` as a Rex SSH host. */
function userRexMachine(machine: string): boolean {
	const userPath = path.join(getAgentDir(), "settings.json");
	return machineSettingsFrom(readJsonObject(userPath), [machine], userPath)?.rex !== undefined;
}

function findProjectRootForSettings(cwd: string): string {
	let current = path.resolve(cwd);
	while (true) {
		if (fs.existsSync(path.join(getProjectConfigDir(current), "settings.json"))) return current;
		const parent = path.dirname(current);
		if (parent === current) return path.resolve(cwd);
		current = parent;
	}
}

/** The child's cwd on a remote machine: an absolute launch cwd, or the launch cwd under the machine's configured root. */
function remoteMachineCwd(stepCwd: string | undefined, root: string | undefined, name: string): string {
	const step = stepCwd?.trim();
	if (step && isRemoteAbsolute(step)) return step;
	if (!root) throw new Error(`No root for ${name} in this repo. Set subagents.machines.${name}.cwd in .pi/settings.json or pass an absolute cwd on that machine.`);
	return step ? path.posix.join(root, step) : root;
}

export function resolveHerdrMachinePlacement(input: ResolveHerdrMachinePlacementInput): HerdrMachinePlacement {
	const requested = validateMachineName(input.machine);
	const catalog = input.catalogJson !== undefined
		? parseMachineCatalog(input.catalogJson)
		: readHerdrMachineCatalog(input.env ?? process.env, input.herdrBin ?? process.env.HERDR_BIN ?? "herdr");
	const selected = selectMachine(catalog, requested);
	const name = selected.label ?? selected.id;
	const keys = [...new Set([requested, ...(selected.label ? [selected.label] : []), selected.id])];
	const settings = input.settings ?? readMachineSettings(input.cwd, keys);
	if (settings?.env && Object.keys(settings.env).length > 0) {
		throw new Error(`Saved-machine environment for '${name}' must be configured remotely. Remove machines.${name}.env and configure the remote Herdr/Pi session instead.`);
	}
	const cwd = remoteMachineCwd(input.stepCwd, settings?.cwd, name);
	return {
		machine: {
			provider: "herdr",
			id: selected.id,
			...(selected.label ? { label: selected.label } : {}),
			target: validateTarget(selected.target, requested),
			...(selected.session && selected.session !== "default" ? { session: selected.session } : {}),
			cwd: validateRemoteCwd(cwd, requested),
		},
		...(settings?.env ? { env: settings.env } : {}),
	};
}

/** Resolves `machine: "local"` inside a Herdr pane: records the server drawing this Pi (confirmed to know this pane) and the real launch directory. */
function resolveHerdrLocalPlacement(input: { cwd: string; stepCwd?: string; env: NodeJS.ProcessEnv; herdrBin?: string }): HerdrLocalMachineReference {
	if (process.platform === "win32") throw new Error("Machine 'local' runs the child in a Herdr pane, which is not supported on Windows.");
	const env = input.env, paneId = env.HERDR_PANE_ID!.trim(), bin = input.herdrBin ?? env.HERDR_BIN ?? "herdr", notFound = `Machine 'local' needs the Herdr CLI, but '${bin}' was not found on PATH.`;
	let endpoint: ReturnType<typeof parseHerdrEndpoint>;
	try { endpoint = parseHerdrEndpoint(runLocalHerdr(bin, ["status", "server", "--json"], env, notFound), env.HERDR_SESSION); } catch (error) { throw new Error(`Machine 'local' could not confirm this pane's Herdr server: ${error instanceof Error ? error.message : String(error)}`, { cause: error }); }
	let pane: unknown;
	try { pane = JSON.parse(runLocalHerdr(bin, ["pane", "get", paneId], herdrLocalEnv(endpoint.socket, endpoint.session, env), notFound)); } catch (error) { throw new Error(`Machine 'local' needs this Pi's Herdr pane ${paneId}, but the Herdr server at ${endpoint.socket} did not return it: ${error instanceof Error ? error.message : String(error)}`, { cause: error }); }
	const result = (pane as { result?: { type?: unknown; pane?: { pane_id?: unknown } } } | null)?.result;
	if (result?.type !== "pane_info" || result.pane?.pane_id !== paneId) throw new Error(`The Herdr server at ${endpoint.socket} did not confirm pane ${paneId}.`);
	return { provider: "herdr", id: REX_LOCAL_MACHINE, socket: endpoint.socket, ...(endpoint.session ? { session: endpoint.session } : {}), cwd: resolveLocalLaunchCwd(input.cwd, input.stepCwd) };
}

function resolveHerdrCoreLocalPlacement(input: { cwd: string; stepCwd?: string; env: NodeJS.ProcessEnv; hcBin?: string }): HerdrCoreLocalMachineReference {
	if (process.platform === "win32") throw new Error("Machine 'local' runs the child in a Herdr Core terminal, which is not supported on Windows.");
	const terminal = input.env.HC_TERMINAL_ID?.trim();
	const socket = input.env.HC_TERMINAL_SOCKET?.trim();
	if (!terminal || !socket || !path.isAbsolute(socket)) throw new Error("Machine 'local' needs HC_TERMINAL_ID and an absolute HC_TERMINAL_SOCKET from Herdr Core.");
	const bin = input.hcBin ?? "hc";
	const result = spawnSync(bin, ["--json", "get", terminal], { env: input.env, encoding: "utf-8", maxBuffer: MAX_HERDR_MACHINE_LIST_BYTES, timeout: HERDR_MACHINE_LIST_TIMEOUT_MS, windowsHide: true });
	if (result.error) throw new Error((result.error as NodeJS.ErrnoException).code === "ENOENT" ? `Machine 'local' needs the Herdr Core CLI, but '${bin}' was not found on PATH.` : `Failed to run hc get ${terminal}: ${result.error.message}`, { cause: result.error });
	if (result.status !== 0) throw new Error(`Machine 'local' could not confirm this Pi's Herdr Core terminal ${terminal}: ${(result.stderr || result.stdout).trim().slice(0, 512)}`);
	let found: { address?: unknown; state?: unknown } | null;
	try { found = JSON.parse(result.stdout); } catch (error) { throw new Error(`Machine 'local' received malformed terminal data from Herdr Core for ${terminal}.`, { cause: error }); }
	if (found?.address !== terminal || found.state !== "live") throw new Error(`Herdr Core did not confirm live parent terminal ${terminal}.`);
	return { provider: "herdr-core", id: REX_LOCAL_MACHINE, socket, parentTerminal: terminal, cwd: resolveLocalLaunchCwd(input.cwd, input.stepCwd) };
}

/** `local` resolves to a child of the terminal this Pi runs in (a new tab in Herdr or Rex, a headless terminal in Herdr Core); a name with a `rex` entry in user settings to a Rex pane on that SSH host; any other value to a Herdr saved machine. */
export function resolveMachinePlacement(input: ResolveHerdrMachinePlacementInput): MachinePlacement {
	const requested = validateMachineName(input.machine);
	const settings = input.settings ?? readMachineSettings(input.cwd, [requested]);
	if (requested === REX_LOCAL_MACHINE) {
		if (settings?.rex) throw new Error("Machine 'local' is reserved for this machine; give the Rex SSH host in subagents.machines.local.rex another name.");
		const env = input.env ?? process.env;
		// Herdr panes and Herdr Core terminals can inherit REX_SESSION; the runtime that directly owns this Pi wins over Rex.
		if (env.HERDR_ENV === "1" && env.HERDR_PANE_ID?.trim()) return { machine: resolveHerdrLocalPlacement({ cwd: input.cwd, stepCwd: input.stepCwd, env, herdrBin: input.herdrBin }) };
		if (env.HC_TERMINAL_ID?.trim()) return { machine: resolveHerdrCoreLocalPlacement({ cwd: input.cwd, stepCwd: input.stepCwd, env, hcBin: input.hcBin }) };
		if (env.REX_SESSION?.trim()) return { machine: resolveRexLocalPlacement({ cwd: input.cwd, stepCwd: input.stepCwd, env }) };
		throw new Error("Machine 'local' opens the child in the terminal this Pi runs in, but this Pi is running in neither Herdr (HERDR_ENV=1 with HERDR_PANE_ID), Herdr Core (HC_TERMINAL_ID), nor Rex (REX_SESSION).");
	}
	if (settings?.rex) return { machine: { provider: "rex", id: requested, target: settings.rex.ssh, cwd: validateRemoteCwd(remoteMachineCwd(input.stepCwd, settings.cwd, requested), requested) } };
	return resolveHerdrMachinePlacement(input);
}

/** A placed Pi keeps its transcript on the pane's machine, so it can't start from a local one. */
export const PLACED_RESTORE_UNSUPPORTED = "Pane-native remote Pi does not support fork, resume, or revival; use fresh context.";

export function formatHerdrMachineRunnerUnsupported(input: {
	machine?: string;
	agentName: string;
	runnerType?: string;
	adapter?: string;
	worktree?: boolean;
}): string | undefined {
	if (input.machine === undefined) return undefined;
	const name = input.machine.trim();
	const local = name === REX_LOCAL_MACHINE;
	let rex: boolean;
	try { rex = local || userRexMachine(name); } catch (error) { return error instanceof Error ? error.message : String(error); }
	if (rex) {
		if (input.runnerType !== undefined && input.runnerType !== "pi") return `Agent '${input.agentName}' requested machine '${name}', but ${local ? "machine 'local' runs" : "Rex supports"} native Pi children only. Remove the machine or use a native Pi agent.`;
		if (input.worktree === true) return `Agent '${input.agentName}' requested machine '${name}', but managed worktrees cannot be combined with machine placement.`;
		if (process.platform === "win32") return `Machine '${name}' runs the child in ${local ? "a Herdr, Herdr Core or Rex terminal" : "a Rex pane"}, which is not supported on Windows.`;
		return undefined;
	}
	if (input.runnerType !== undefined && input.runnerType !== "pi" && input.runnerType !== "external-cli") {
		return `Agent '${input.agentName}' requested machine '${input.machine}', but this runner cannot use pane-native Herdr placement. Use native Pi or a built-in Claude, Codex, or Cursor profile.`;
	}
	if (input.runnerType === "external-cli" && (input.adapter === undefined || !SUPPORTED_MACHINE_ADAPTERS.has(input.adapter))) {
		return `Agent '${input.agentName}' requested machine '${input.machine}', but generic external-cli commands cannot be remote-wrapped safely. Use claude-code, claude-code-writer, codex-exec, codex-exec-writer, cursor-agent, or cursor-agent-writer.`;
	}
	if (input.worktree === true) return `Agent '${input.agentName}' requested machine '${input.machine}', but managed worktrees are local git operations and cannot be combined with a Herdr saved machine.`;
	if (process.platform === "win32") return "Herdr saved-machine pane transport requires hardened OpenSSH StreamLocal forwarding, which is not supported from a Windows host yet.";
	return undefined;
}

/** Legacy local-child SSH wrapping is intentionally unavailable after the pane-native cut-over. */
export function prepareHerdrMachineExternalCliRun(input: RunExternalCliInput, placement: HerdrMachinePlacement | undefined, _options: { localCwd: string }): PreparedHerdrMachineExternalCliRun {
	if (placement) throw new Error("Saved-machine external profiles must run in a Herdr-owned pane.");
	return { input, decorateProcess: (process) => process };
}
const HINTS: ReadonlyArray<readonly [RegExp, (machine: HerdrMachineReference) => string]> = [
	[/Host key verification failed|REMOTE HOST IDENTIFICATION HAS CHANGED|Permission denied \(publickey|Permission denied, please try again|No such identity|Could not resolve hostname|Connection (timed out|refused)/iu,
		(machine) => `ssh could not reach or authenticate with ${machine.target}. Connect once interactively with ssh ${machine.target} to accept the host key or fix the identity; BatchMode never prompts.`],
	[/is not recognized as|CommandNotFoundException|PowerShell|At line:\d+ char:\d+/u,
		(machine) => `Machine '${machine.label ?? machine.id}' is not a POSIX host. External-cli runs support POSIX ssh targets only.`],
	[/\bcd: .*(No such file or directory|not a directory|can't cd)|exit(?:ed with)? code 125\b/iu,
		(machine) => `Nothing at ${machine.cwd} on ${machine.label ?? machine.id}. Clone the repo there first; pi-subagents never clones, pulls, or checks out on a machine.`],
	[/(?:command not found|not found)\s*$|No such file or directory\s*$|exit(?:ed with)? code 127\b/imu,
		(machine) => `The agent CLI was not found on ${machine.label ?? machine.id}. Non-interactive shells skip rc files and the PATH prefix did not find it; set the agent's command to the absolute path on that machine.`],
	[/not logged in|unauthorized|authentication_error|invalid api key|please run .*login|OAuth token/iu,
		(machine) => `Remote runs use the machine's own credentials. Log in to the agent CLI on ${machine.label ?? machine.id} once.`],
];

/** One-line operator hint for a predictable remote failure, matched against error text and the stderr tail. */
export function formatHerdrMachineHint(machine: HerdrMachineReference, text: string): string | undefined {
	for (const [pattern, hint] of HINTS) if (pattern.test(text)) return hint(machine);
	return undefined;
}
