#!/usr/bin/env bash
# Auto-rebuild MCP server binary when element-tool source files change.
#
# Why: `out/mcp-server.cjs` is the active binary loaded by Claude Code /
# Codex CLI / Cursor MCP clients. It's a build artifact (gitignored) and
# does NOT refresh on its own. Without this hook, you can ship 94 new v1
# builders to source but external MCP clients see 0 of them — exactly what
# happened on 2026-05-03 when codex CLI + gpt-5.5 generated 138 nodes and
# used 0 v1 tools because mcp-server.cjs was the Apr 20 build.
#
# Triggered when the just-finished commit touched any of:
#   - packages/pen-core/src/element-builders/
#   - packages/pen-mcp/src/tools/  (handlers + element-tool-helpers.ts)
#   - packages/pen-mcp/src/routes/element-tool-*.ts  (defs + def-props shared schemas)
#   - packages/pen-ai-skills/skills/phases/generation/elements*.md
#
# Note: post-commit runs AFTER the commit lands. The rebuild's output
# (out/mcp-server.cjs) is gitignored, so we don't pollute the commit.
# Open MCP clients still need to restart to pick up the new binary
# (MCP server processes don't hot-reload).

set -euo pipefail

CHANGED=$(git diff-tree --no-commit-id --name-only -r HEAD)

NEEDS_REBUILD=$(echo "$CHANGED" | grep -E '^(packages/pen-core/src/element-builders/|packages/pen-mcp/src/tools/|packages/pen-mcp/src/routes/element-tool-|packages/pen-ai-skills/skills/phases/generation/elements)' || true)

if [ -z "$NEEDS_REBUILD" ]; then
  exit 0
fi

echo "[post-commit] element-tool source changed — rebuilding MCP server binary..."
if bun run mcp:compile > /tmp/post-commit-mcp-compile.log 2>&1; then
  SIZE=$(wc -c < out/mcp-server.cjs | tr -d ' ')
  echo "[post-commit] mcp:compile OK — out/mcp-server.cjs is now ${SIZE} bytes"
  echo "[post-commit] open Claude Code / Codex CLI sessions need restart to pick up new binary"
else
  echo "[post-commit] mcp:compile FAILED — see /tmp/post-commit-mcp-compile.log"
  echo "[post-commit] (commit was kept; rebuild manually with: bun run mcp:compile)"
  exit 0  # don't fail the commit; the source change is already committed
fi
