/**
 * Child tool plan: which builtin tools, MCP tools, runtime hooks, and extension
 * files a child launch gets, and how that resolution is reported. Both the
 * foreground path and the async runner build their session launch from this.
 */
import { createHash } from "node:crypto";
import * as fs from "node:fs";
import * as path from "node:path";
import { fileURLToPath } from "node:url";
import {
	formatUnresolvedBuiltinMcpSelectors,
	formatUnresolvedMcpDirectToolSelectors,
	resolveMcpDirectToolResolution,
	type McpRuntimeSnapshotHost,
	type ResolvedMcpDirectToolSelection,
} from "./mcp-direct-tool-allowlist.ts";
import {
	TEMP_ROOT_DIR,
	type FastServiceTier,
	type JsonSchemaObject,
	type LaunchResolvedChildExtensions,
} from "../../shared/types.ts";
import { THINKING_LEVELS, type ModelInfo } from "../../shared/model-info.ts";
import { getAgentDir } from "../../shared/utils.ts";
import { resolveRuntimeModulePath, RUNTIME_MODULE_EXTENSIONS } from "../../shared/runtime-module-path.ts";
import type { PermissionRules } from "./permissions.ts";
import { snapshotRequiredChildExtensions, type RequiredChildExtensionSnapshot } from "../../shared/required-child-extensions.ts";
import {
	capabilityCeilingAgentRestrictionSources,
	intersectSubagentCapabilityCeilings,
	isAgentAllowedByCapabilityCeiling,
	type ResolvedSubagentCapabilityCeiling,
	type SubagentCapabilityAudit,
} from "./capability-ceiling.ts";

const MAX_LAUNCH_RESOLVED_EXTENSION_IDS = 32;
const RUNTIME_EXTENSION_DIR = path.dirname(fileURLToPath(import.meta.url));
const FANOUT_CHILD_EXTENSION_DIR = path.join(RUNTIME_EXTENSION_DIR, "..", "..", "extension");

const SUBAGENT_RUNTIME_EXTENSION_PATHS = new Set([
	path.join(RUNTIME_EXTENSION_DIR, "subagent-prompt-runtime"),
	path.join(FANOUT_CHILD_EXTENSION_DIR, "fanout-child"),
].flatMap((base) => RUNTIME_MODULE_EXTENSIONS.map((extension) => path.normalize(`${base}${extension}`))));

/** True for the extension files pi-subagents itself installs in child sessions. */
export function isSubagentRuntimeExtensionPath(extensionPath: string): boolean {
	return SUBAGENT_RUNTIME_EXTENSION_PATHS.has(path.normalize(extensionPath));
}
const OPENAI_PROMPT_CACHE_KEY_MAX_LENGTH = 64;
export function deriveForkPromptCacheKey(parentSessionId: string | undefined): string | undefined {
	const parent = parentSessionId?.trim();
	if (!parent) return undefined;
	const digest = createHash("sha256").update(parent).digest("hex").slice(0, OPENAI_PROMPT_CACHE_KEY_MAX_LENGTH - "pi-fork:".length);
	return `pi-fork:${digest}`;
}

function sanitizeSupervisorChannelSegment(value: string): string {
	return (
		value
			.trim()
			.replace(/[^A-Za-z0-9._-]+/g, "-")
			.replace(/^-+|-+$/g, "") || "unknown"
	);
}

export function supervisorChannelDir(
	runId: string,
	agent: string,
	childIndex: number,
): string {
	return path.join(
		TEMP_ROOT_DIR,
		"supervisor-channels",
		`${sanitizeSupervisorChannelSegment(runId)}-${sanitizeSupervisorChannelSegment(agent)}-${childIndex}`,
	);
}

export function applyThinkingSuffix(
	model: string | undefined,
	thinking: string | false | undefined,
	replaceExisting = false,
): string | undefined {
	if (!model || !thinking) return model;
	const colonIdx = model.lastIndexOf(":");
	if (
		colonIdx !== -1 &&
		THINKING_LEVELS.some((level) => level === model.substring(colonIdx + 1))
	) {
		return replaceExisting ? `${model.slice(0, colonIdx)}:${thinking}` : model;
	}
	return `${model}:${thinking}`;
}

export function fastModeUnsupportedError(reason: string, serviceTier?: FastServiceTier): Error {
	return new Error(
		`Cannot forward fast mode${serviceTier ? ` service_tier '${serviceTier}'` : ""}: ${reason}. Select a model using Pi's OpenAI Responses or Codex Responses adapter, or set fast: false.`,
	);
}

export function isFastModeAdapter(api: string): boolean {
	return api === "openai-responses" || api === "openai-codex-responses";
}

export interface ResolvePiLaunchToolPlanInput {
	tools?: string[];
	excludeTools?: string[];
	allowNestedSubagents?: boolean;
	extensions?: string[];
	subagentOnlyExtensions?: string[];
	requiredExtensions?: RequiredChildExtensionSnapshot;
	mcpDirectTools?: string[];
	cwd?: string;
	requireReadTool?: boolean;
	structuredOutput?:
		| boolean
		| {
				schema: JsonSchemaObject;
				schemaPath: string;
				outputPath: string;
		  };
	fast?: boolean;
	modelInfo?: Pick<ModelInfo, "fullId" | "api">;
	capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
	inheritedCapabilityCeiling?: ResolvedSubagentCapabilityCeiling;
	agentName?: string;
	permissionRules?: PermissionRules;
	runtimeSnapshotHost?: McpRuntimeSnapshotHost;
	/** The parent's built-in MCP selections; the background runner has no host to resolve selectors against. */
	builtinMcpTools?: ResolvedMcpDirectToolSelection[];
}

export interface PiLaunchToolPlan {
	capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
	requestedBuiltinTools: string[];
	declaredBuiltinTools: string[];
	excludeTools: string[];
	toolExtensionPaths: string[];
	resolvedMcpSelections: ResolvedMcpDirectToolSelection[];
	effectiveMcpSelections: ResolvedMcpDirectToolSelection[];
	effectiveMcpTools: string[];
	/** Effective selections granted from Pi's built-in MCP; undefined when the selectors did not resolve against it. */
	builtinMcpTools?: ResolvedMcpDirectToolSelection[];
	explicitToolAllowlist: boolean;
	internalTools: string[];
	effectiveToolAllowlist: string[];
	requiredChildTools: string[];
	fanoutAuthorized: boolean;
	runtimeExtensions: string[];
	configuredExtensions: string[];
	requiredExtensions: RequiredChildExtensionSnapshot;
	extensionArgs: string[];
	disableAmbientExtensions: boolean;
	capabilityAudit?: SubagentCapabilityAudit;
}

function extensionIdentifier(value: string): string {
	return `sha256:${createHash("sha256").update(path.normalize(value.trim())).digest("hex").slice(0, 16)}`;
}

function boundedExtensionIdentifiers(values: string[]): {
	ids: string[];
	omitted: number;
} {
	const ids = [...new Set(values.map(extensionIdentifier))];
	return {
		ids: ids.slice(0, MAX_LAUNCH_RESOLVED_EXTENSION_IDS),
		omitted: Math.max(0, ids.length - MAX_LAUNCH_RESOLVED_EXTENSION_IDS),
	};
}

function hasPermissionRules(rules: PermissionRules | undefined): boolean {
	return rules !== undefined && Object.keys(rules).length > 0;
}

/**
 * Children are pi sessions inside the parent or the runner process; a spawned
 * `pi` received extra MCP server definitions as a CLI argument, but a session
 * has no such input. Selecting a server that exists only in pi-mcp-adapter's
 * runtime snapshot therefore cannot work and fails the launch.
 */
export function formatRuntimeSnapshotMcpServersError(agentName: string | undefined, serverNames: readonly string[]): string {
	const subject = agentName ? `Agent '${agentName}'` : "Subagent";
	return `${subject} selects MCP tools from servers that exist only in pi-mcp-adapter's runtime snapshot (${serverNames.join(", ")}). MCP servers from the runtime snapshot cannot be provided to in-process children; MCP tools must come from an ambient adapter extension in a background child (\`async: true\`), so add the server to the adapter's configuration file instead.`;
}

/** Path-like entries load extensions instead of naming tools, so Pi never reads them as modifiers. */
function isToolExtensionPath(entry: string): boolean {
	return entry.includes("/") || entry.endsWith(".ts") || entry.endsWith(".js");
}

/**
 * A child's `tools` list is a complete allowlist. Read as names, Pi's modifier
 * entries would become required tools no child has, or mix with the names the
 * plan adds into a list Pi rejects. The modifier rule is Pi's `isToolModifier`:
 * a `+name` or `-name` entry edits Pi's default tool selection.
 */
export function assertNoToolModifierEntries(agentName: string | undefined, tools: readonly string[]): void {
	const entries = tools.filter((entry) => /^[+-]/u.test(entry) && !isToolExtensionPath(entry));
	if (entries.length === 0) return;
	const subject = agentName ? `Agent '${agentName}'` : "Subagent";
	throw new Error(`${subject} lists Pi tool modifier ${entries.length === 1 ? "entry" : "entries"} in \`tools\`: ${entries.join(", ")}. A child's \`tools\` list is the complete set of tools it gets, so +name and -name entries are not supported; name every tool the child needs, or omit \`tools\` and use \`excludeTools\` to drop one.`);
}

export function projectLaunchResolvedChildExtensions(
	toolPlan: Pick<
		PiLaunchToolPlan,
		| "runtimeExtensions"
		| "configuredExtensions"
		| "requiredExtensions"
		| "extensionArgs"
		| "disableAmbientExtensions"
	>,
): LaunchResolvedChildExtensions {
	const runtime = boundedExtensionIdentifiers(toolPlan.runtimeExtensions);
	const configured = boundedExtensionIdentifiers(toolPlan.configuredExtensions);
	const effective = boundedExtensionIdentifiers(toolPlan.extensionArgs);
	return {
		version: 1,
		source: "launch-resolved",
		disableAmbientExtensions: toolPlan.disableAmbientExtensions,
		runtime: runtime.ids,
		configured: configured.ids,
		required: toolPlan.requiredExtensions.map(({ id }) => id),
		effective: effective.ids,
		omitted: {
			runtime: runtime.omitted,
			configured: configured.omitted,
			required: 0,
			effective: effective.omitted,
		},
	};
}

/**
 * Returns the absolute path to the extension's main module, or undefined
 * when the package is not installed. Callers can check `autoInject` config
 * to decide whether to include it in child sessions.
 */
export function resolvePermissionSystemExtension(): string | undefined {
	const agentDir = getAgentDir();
	const candidates = [
		// npm-scoped package (most common)
		path.join(
			agentDir,
			"npm",
			"node_modules",
			"@gotgenes",
			"pi-permission-system",
		),
		// direct extension directory (some layouts)
		path.join(agentDir, "extensions", "pi-permission-system"),
	];
	const errors: Error[] = [];
	for (const extDir of candidates) {
		if (!fs.existsSync(extDir)) continue;
		const pkgPath = path.join(extDir, "package.json");
		if (!fs.existsSync(pkgPath)) {
			errors.push(new Error(`Permission-system package manifest is missing at ${pkgPath}.`));
			continue;
		}
		try {
			let pkg: { pi?: { extensions?: string[] } };
			const parsed: unknown = JSON.parse(fs.readFileSync(pkgPath, "utf-8"));
			if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
				throw new Error("manifest root must be an object");
			}
			pkg = parsed as typeof pkg;
			const extensions = pkg.pi?.extensions;
			const entry = Array.isArray(extensions) ? extensions[0] : undefined;
			if (typeof entry !== "string" || !entry.trim()) {
				throw new Error(
					`Permission-system package manifest at ${pkgPath} must declare pi.extensions[0] as a non-empty string.`,
				);
			}
			const resolved = path.resolve(extDir, entry);
			if (fs.existsSync(resolved)) return resolved;
			throw new Error(
				`Permission-system extension entry ${JSON.stringify(entry)} in ${pkgPath} does not exist at ${resolved}.`,
			);
		} catch (error) {
			const message = error instanceof Error ? error.message : String(error);
			errors.push(message.startsWith("Permission-system") ? new Error(message) : new Error(`Cannot read permission-system package manifest at ${pkgPath}: ${message}`));
		}
	}
	if (errors.length > 0) throw errors[0]!;
	return undefined;
}

export function resolvePiLaunchToolPlan(
	input: ResolvePiLaunchToolPlanInput,
): PiLaunchToolPlan {
	const capabilityCeiling = intersectSubagentCapabilityCeilings(
		input.capabilityCeiling,
		input.inheritedCapabilityCeiling,
	);
	const requiredExtensions = snapshotRequiredChildExtensions(input.requiredExtensions ?? []);
	if (requiredExtensions.length > 0 && capabilityCeiling?.denyExtensions) {
		throw new Error(`Capability ceiling from ${capabilityCeiling.sources.join(", ") || "unknown source"} denies extensions but this host requires: ${requiredExtensions.map(({ id }) => id).join(", ")}.`);
	}
	const allowedToolSet =
		capabilityCeiling?.allowedTools === undefined
			? undefined
			: new Set(capabilityCeiling.allowedTools);
	const requestedBuiltinTools = input.tools?.filter((tool) => !isToolExtensionPath(tool)) ?? [];
	assertNoToolModifierEntries(input.agentName, input.tools ?? []);
	if (input.requireReadTool && allowedToolSet && !allowedToolSet.has("read")) {
		throw new Error(
			`Capability ceiling from ${capabilityCeiling?.sources.join(", ") || "unknown source"} excludes required tool 'read' for lazy skill loading.`,
		);
	}
	const ceilingFilteredBuiltinTools =
		input.tools === undefined
			? allowedToolSet
				? [...allowedToolSet].filter((tool) => tool !== "subagent_command")
				: []
			: (input.requireReadTool &&
				requestedBuiltinTools.length > 0 &&
				!requestedBuiltinTools.includes("read") &&
				!allowedToolSet
					? ["read", ...requestedBuiltinTools]
					: requestedBuiltinTools
				).filter((tool) => !allowedToolSet || allowedToolSet.has(tool));
	const declaredBuiltinTools = ceilingFilteredBuiltinTools;
	const excludeTools = [...new Set((input.excludeTools ?? []).map((tool) => tool.trim()).filter(Boolean))];
	const excludedToolSet = new Set(excludeTools);
	const effectiveDeclaredBuiltinTools = declaredBuiltinTools.filter((tool) => !excludedToolSet.has(tool));
	const fanoutAuthorized = effectiveDeclaredBuiltinTools.includes("subagent") || (
		input.allowNestedSubagents === true &&
		!excludedToolSet.has("subagent") &&
		(!allowedToolSet || allowedToolSet.has("subagent"))
	);
	const toolExtensionPaths: string[] = capabilityCeiling?.denyExtensions
		? []
		: (input.tools ?? []).filter(isToolExtensionPath);
	const mcpResolution = capabilityCeiling?.denyExtensions
		? { selections: [], unresolvedSelectors: [] }
		: input.builtinMcpTools
			// The runner applies the same ceilings again; filtering is idempotent.
			? { selections: input.builtinMcpTools, unresolvedSelectors: [], builtin: true as const }
			: resolveMcpDirectToolResolution(input.mcpDirectTools, input.cwd, input.runtimeSnapshotHost);
	if (mcpResolution.runtimeServerNames?.length) {
		throw new Error(formatRuntimeSnapshotMcpServersError(input.agentName, mcpResolution.runtimeServerNames));
	}
	if (mcpResolution.unresolvedSelectors.length > 0) {
		throw new Error(mcpResolution.builtin
			? formatUnresolvedBuiltinMcpSelectors(input.agentName, mcpResolution.unresolvedSelectors)
			: formatUnresolvedMcpDirectToolSelectors(mcpResolution.unresolvedSelectors));
	}
	const resolvedMcpSelections = mcpResolution.selections;
	const resolvedMcpNames = new Set(resolvedMcpSelections.map((selection) => selection.name));
	const legacyMcpNameCounts = mcpResolution.builtin ? new Map<string, number>() : countLegacyUnderscoreMcpToolNames(resolvedMcpSelections);
	const effectiveMcpSelections = resolvedMcpSelections.filter(
		(selection) =>
			!allowedToolSet ||
			allowedToolSet.has(selection.name) ||
			isLegacyUnderscoreMcpToolAllowed(selection, allowedToolSet, resolvedMcpNames, legacyMcpNameCounts),
	).filter((selection) => !excludedToolSet.has(selection.name));
	const effectiveMcpTools = effectiveMcpSelections.map(
		(selection) => selection.name,
	);
	const builtinMcpTools = mcpResolution.builtin ? effectiveMcpSelections : undefined;
	const explicitToolAllowlist =
		input.tools !== undefined ||
		(input.mcpDirectTools?.length ?? 0) > 0 ||
		allowedToolSet !== undefined;
	const internalTools = (input.structuredOutput ? ["structured_output"] : []).filter((tool) => !excludedToolSet.has(tool));
	const effectiveToolAllowlist = [
		...new Set([
			...effectiveDeclaredBuiltinTools,
			...effectiveMcpTools,
			...internalTools,
		]),
	];
	// Upward contact stays in the --tools allowlist but is not a strict
	// requirement: children register contact_supervisor at runtime through
	// the native supervisor channel (or pi-intercom). The pre-0.50 bridge always
	// appended intercom alongside contact_supervisor, so that exact pairing is
	// legacy plumbing, not a user demand for an external intercom provider;
	// a lone intercom entry stays strictly required (#1207).
	const legacySupervisorPairing = effectiveDeclaredBuiltinTools.includes("contact_supervisor");
	const requiredChildTools = explicitToolAllowlist
		? [
				...new Set([
					...(input.tools !== undefined ? effectiveDeclaredBuiltinTools : []),
					...(input.mcpDirectTools?.length ? effectiveMcpTools : []),
					...internalTools,
				].filter((tool) => tool !== "contact_supervisor" && (!legacySupervisorPairing || tool !== "intercom"))),
			]
		: [];
	const permSystemExt = capabilityCeiling?.denyExtensions
		? undefined
		: hasPermissionRules(input.permissionRules)
			? resolvePermissionSystemExtension()
			: undefined;
	if (input.fast && capabilityCeiling?.denyExtensions) throw new Error("fast mode is not allowed when the launch denies extensions; set fast: false.");
	if (input.fast && input.modelInfo?.api !== undefined && !isFastModeAdapter(input.modelInfo.api)) {
		throw fastModeUnsupportedError(`'${input.modelInfo.fullId}' uses '${input.modelInfo.api}'`);
	}
	// Resolved per launch: an in-place package update can swap a sibling's .ts for .js.
	const runtimeExtensions = [
		resolveRuntimeModulePath(RUNTIME_EXTENSION_DIR, "subagent-prompt-runtime"),
		...(fanoutAuthorized ? [resolveRuntimeModulePath(FANOUT_CHILD_EXTENSION_DIR, "fanout-child")] : []),
		...(permSystemExt ? [permSystemExt] : []),
	];
	const disableAmbientExtensions =
		capabilityCeiling?.denyExtensions === true ||
		input.extensions !== undefined;
	const configuredExtensions = capabilityCeiling?.denyExtensions
		? []
		: [
				...toolExtensionPaths,
				...(input.extensions ?? []),
				...(input.subagentOnlyExtensions ?? []),
			];
	const ordinaryExtensionArgs = disableAmbientExtensions
		? [...new Set([...runtimeExtensions, ...configuredExtensions])]
		: [
				...new Set([
					...runtimeExtensions,
					...toolExtensionPaths,
					...(input.subagentOnlyExtensions ?? []),
				]),
			];
	// Host-required paths have final precedence and cannot be removed by agent defaults or overrides.
	const extensionArgs = [...new Set([...ordinaryExtensionArgs, ...requiredExtensions.map(({ path }) => path)])];
	const requestedToolNames =
		input.tools !== undefined
			? [
					...new Set([
						...requestedBuiltinTools,
						...resolvedMcpSelections.map((selection) => selection.name),
					]),
				]
			: undefined;
	const capabilityAudit = capabilityCeiling
		? ({
				ceiling: capabilityCeiling,
				...(requestedToolNames ? { requestedTools: requestedToolNames } : {}),
				effectiveTools: effectiveToolAllowlist,
				...(excludeTools.length > 0 ? { excludeTools } : {}),
				removedTools:
					requestedToolNames?.filter(
						(tool) => !effectiveToolAllowlist.includes(tool),
					) ?? [],
				internalTools,
				extensionsDenied: capabilityCeiling.denyExtensions,
				removedExtensionCount: capabilityCeiling.denyExtensions
					? (input.extensions?.length ?? 0) +
						(input.subagentOnlyExtensions?.length ?? 0) +
						(input.tools ?? []).filter(isToolExtensionPath).length
					: 0,
				requestedMcpToolCount: input.mcpDirectTools?.length ?? 0,
				effectiveMcpTools,
				agentAllowed:
					input.agentName === undefined
						? true
						: isAgentAllowedByCapabilityCeiling(
								input.agentName,
								capabilityCeiling,
							),
				...(capabilityCeilingAgentRestrictionSources(capabilityCeiling)
					? {
							agentRestrictionSources:
								capabilityCeilingAgentRestrictionSources(capabilityCeiling),
						}
					: {}),
			} satisfies SubagentCapabilityAudit)
		: undefined;
	return {
		...(capabilityCeiling ? { capabilityCeiling } : {}),
		requestedBuiltinTools,
		declaredBuiltinTools,
		excludeTools,
		toolExtensionPaths,
		resolvedMcpSelections,
		effectiveMcpSelections,
		effectiveMcpTools,
		builtinMcpTools,
		explicitToolAllowlist,
		internalTools,
		effectiveToolAllowlist,
		requiredChildTools,
		fanoutAuthorized,
		runtimeExtensions,
		configuredExtensions,
		requiredExtensions,
		extensionArgs,
		disableAmbientExtensions,
		...(capabilityAudit ? { capabilityAudit } : {}),
	};
}

// Capability ceilings persisted before #1685 may still name hyphenated MCP server prefixes with underscores.
function countLegacyUnderscoreMcpToolNames(selections: readonly ResolvedMcpDirectToolSelection[]): Map<string, number> {
	const counts = new Map<string, number>();
	for (const selection of selections) {
		const legacyName = legacyUnderscoreMcpToolName(selection);
		if (legacyName !== selection.name) counts.set(legacyName, (counts.get(legacyName) ?? 0) + 1);
	}
	return counts;
}

function isLegacyUnderscoreMcpToolAllowed(
	selection: ResolvedMcpDirectToolSelection,
	allowedToolSet: ReadonlySet<string>,
	resolvedMcpNames: ReadonlySet<string>,
	legacyMcpNameCounts: ReadonlyMap<string, number>,
): boolean {
	const legacyName = legacyUnderscoreMcpToolName(selection);
	return legacyMcpNameCounts.get(legacyName) === 1 && !resolvedMcpNames.has(legacyName) && allowedToolSet.has(legacyName);
}

function legacyUnderscoreMcpToolName(selection: ResolvedMcpDirectToolSelection): string {
	const slash = selection.selector.indexOf("/");
	if (slash < 1) return selection.name;
	const toolName = selection.selector.slice(slash + 1);
	const suffix = `_${toolName}`;
	if (!selection.name.endsWith(suffix)) return selection.name;
	const prefix = selection.name.slice(0, -suffix.length);
	return `${prefix.replace(/-/g, "_")}${suffix}`;
}
