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

mkdir -p profile

uv run python -m cProfile -o profile/cpu.prof -m pytest >/dev/null
uv run python -c "
import pstats
stats = pstats.Stats('profile/cpu.prof')
stats.sort_stats('cumulative')
with open('profile/cpu-top.txt', 'w') as f:
    stats.stream = f
    stats.print_stats(30)
"

if ! uv run python -c "import memray" >/dev/null 2>&1; then
  echo "note: memray not installed — install it for memory profiling:" >&2
  echo "  uv sync --extra profiling" >&2
else
  uv run memray run --force -o profile/memray.bin -m pytest >/dev/null
  uv run memray stats --force -o profile/mem-top.txt profile/memray.bin
fi

{
  echo "# Generated server bottleneck report"
  echo
  echo "Generated $(date -u +%Y-%m-%dT%H:%M:%SZ)."
  echo
  if [ -f coverage.json ]; then
    echo "## Coverage summary"
    echo
    echo '```'
    uv run python -c "
import json
with open('coverage.json') as f:
    data = json.load(f)
files = sorted(data['files'].items(), key=lambda kv: kv[1]['summary']['percent_covered'])
for path, info in files[:20]:
    pct = info['summary']['percent_covered']
    print(f'{pct:6.1f}% covered  {path}')
"
    echo '```'
    echo
  fi
  echo "## Hottest functions (CPU, cumulative time)"
  echo
  echo '```'
  tail -n +6 profile/cpu-top.txt | head -20
  echo '```'
  if [ -f profile/mem-top.txt ]; then
    echo
    echo "## Memory summary"
    echo
    echo '```'
    cat profile/mem-top.txt
    echo '```'
  fi
} > profile/bottleneck-report.md

echo
echo "Profile written to:"
echo "  profile/cpu.prof, profile/cpu-top.txt     (LLM/tool-ingestable — cProfile)"
if [ -f profile/memray.bin ]; then
  echo "  profile/memray.bin, profile/mem-top.txt   (memray — run 'uv run memray flamegraph profile/memray.bin' for an interactive view)"
fi
echo "  profile/bottleneck-report.md              (combined coverage + hot-path summary; run scripts/coverage.sh first for the coverage section)"
