/**
 * Hook tools — provides Claude Code hook configuration for activity bridging.
 */
import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import type { HookBridge } from "../hook-bridge.ts";

export function registerHookTools(mcp: McpServer, hookBridge: HookBridge) {
	mcp.tool(
		"get_hook_config",
		'Returns Claude Code hook configuration JSON for bridging activity to the Abracadabra dashboard. Copy the "hooks" object into your .claude/settings.json (or settings.local.json) to enable real-time tool-call activity cards in the chat, visible to all connected users.',
		{},
		async () => {
			const config = { hooks: buildHookConfig(hookBridge.portFile) };
			return {
				content: [
					{
						type: "text",
						text: JSON.stringify(config, null, 2),
					},
				],
			};
		},
	);
}

/**
 * Build the Claude Code `hooks` object. We use a `command` hook (not `http`)
 * that reads the bridge's port file at execution time and POSTs the event
 * JSON (received on stdin) to it. This survives MCP restarts that pick a new
 * random port — the URL is resolved fresh each call instead of being baked in.
 *
 * The command is a no-op (`exit 0`) when the port file is missing or curl
 * fails, so a stopped bridge never blocks a tool call.
 */
export function buildHookConfig(portFile: string): Record<string, unknown> {
	const cmd = `P=$(cat ${JSON.stringify(portFile)} 2>/dev/null); [ -n "$P" ] && curl -s -m 3 -X POST "http://127.0.0.1:$P/hook" --data-binary @- >/dev/null 2>&1; exit 0`;
	const hookEntry = { type: "command", command: cmd, timeout: 5 };
	const events = [
		"UserPromptSubmit",
		"PreToolUse",
		"PostToolUse",
		"SubagentStart",
		"SubagentStop",
		"Stop",
	];
	const hooks: Record<string, unknown> = {};
	for (const ev of events) {
		hooks[ev] = [{ hooks: [hookEntry] }];
	}
	return hooks;
}
