#!/usr/bin/env bash
# {{ display_name }} MCP server — generated by mcpify. Do not hand-edit.
# Profiles a real one-shot `search` invocation of the built server via
# Tools/Profiler (Microsoft.Diagnostics.NETCore.Client). Run
# scripts/coverage.sh first if you want the coverage section below to be
# populated too — this script only profiles, it doesn't run tests.
set -euo pipefail
cd "$(dirname "$0")/.."

if ! command -v dotnet-trace >/dev/null 2>&1; then
  echo "error: dotnet-trace not found. Install it with:" >&2
  echo "  dotnet tool install --global dotnet-trace" >&2
  exit 1
fi

mkdir -p profile
dotnet run --project Tools/Profiler

dotnet-trace convert --format Speedscope profile/test_profile.nettrace -o profile/test_profile

python3 scripts/speedscope_to_text.py \
  profile/test_profile.speedscope.json \
  profile/folded-stacks.txt \
  profile/cpu-top.txt

{
  echo "# Generated server bottleneck report"
  echo
  echo "Generated $(date -u +%Y-%m-%dT%H:%M:%SZ)."
  echo
  if ls TestResults/**/coverage.cobertura.xml >/dev/null 2>&1; then
    echo "## Coverage summary"
    echo
    echo '```'
    python3 -c "
import glob, xml.etree.ElementTree as ET
files = glob.glob('TestResults/**/coverage.cobertura.xml', recursive=True)
root = ET.parse(sorted(files)[-1]).getroot()
rows = []
for cls in root.iter('class'):
    rate = float(cls.get('line-rate', '0')) * 100
    rows.append((rate, cls.get('filename')))
for rate, name in sorted(rows)[:20]:
    print(f'{rate:6.1f}% covered  {name}')
"
    echo '```'
    echo
  fi
  echo "## Hottest functions (CPU + GC, self weight)"
  echo
  echo '```'
  tail -n +2 profile/cpu-top.txt | head -20
  echo '```'
} > profile/bottleneck-report.md

echo
echo "Profile written to:"
echo "  profile/test_profile.nettrace              (interactive — open in Visual Studio or PerfView)"
echo "  profile/test_profile.speedscope.json        (interactive — load at https://www.speedscope.app)"
echo "  profile/cpu-top.txt, profile/folded-stacks.txt (LLM/tool-ingestable)"
echo "  profile/bottleneck-report.md                (combined coverage + hot-path summary)"
