#!/usr/bin/env bash
# {{ display_name }} MCP server — generated by mcpify. Do not hand-edit.
set -euo pipefail
cd "$(dirname "$0")/.."

mkdir -p profile/heap
rm -f isolate-*.log ./*.heapprofile
rm -rf profile/heap && mkdir -p profile/heap

node --prof --heap-prof node_modules/.bin/vitest run

# Vitest forks a worker process per test file — the parent's --prof output
# is one isolate log, but --heap-prof is inherited by every fork, so there
# can be many .heapprofile files.
mv isolate-*.log profile/isolate.log
mv ./*.heapprofile profile/heap/

node --prof-process profile/isolate.log > profile/cpu-profile.txt 2>/dev/null
node scripts/heap-profile-summary.js profile/heap/*.heapprofile profile/heap-top.txt

{
  echo "# Generated server bottleneck report"
  echo
  echo "Generated $(date -u +%Y-%m-%dT%H:%M:%SZ)."
  echo
  echo "## Hottest functions (CPU)"
  echo
  echo '```'
  sed -n '/\[Summary\]/,/\[C++ entry points\]/p' profile/cpu-profile.txt
  echo '```'
  echo
  echo "## Hottest allocators (memory)"
  echo
  echo '```'
  tail -n +2 profile/heap-top.txt | head -20
  echo '```'
} > profile/bottleneck-report.md

echo
echo "Profile written to:"
echo "  profile/cpu-profile.txt   (LLM/tool-ingestable — node --prof-process output)"
echo "  profile/heap-top.txt      (LLM/tool-ingestable — top allocators)"
echo "  profile/heap/*.heapprofile (interactive — load in Chrome DevTools' Memory tab)"
echo "  profile/bottleneck-report.md (combined hot-path summary)"
