#!/usr/bin/env bash
# Bitbucket Data Center MCP server — generated by mcpify. Do not hand-edit.
# CPU profiling via samply (works on macOS/Linux without sudo/dtrace) plus
# opt-in heap profiling via dhat-rs (cargo build --features profiling).
set -euo pipefail
cd "$(dirname "$0")/.."

if ! command -v samply >/dev/null 2>&1; then
  echo "error: samply not found. Install it with:" >&2
  echo "  cargo install samply" >&2
  echo "  samply setup   # macOS only: codesigns samply for process attach" >&2
  exit 1
fi

mkdir -p profile
cargo build --release --features profiling

samply record --save-only --unstable-presymbolicate -o profile/profile.json.gz -- \
  ./target/release/bitbucket-dc-mcp search "test query"

python3 scripts/samply_to_text.py \
  profile/profile.json.gz \
  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 [ -f target/coverage/lcov.info ]; then
    echo "## Coverage gaps"
    echo
    echo '```'
    awk '
      /^SF:/ { file=substr($0,4); hit=0; total=0 }
      /^DA:/ { total++; split($0,a,","); if (a[2]+0 > 0) hit++ }
      /^end_of_record/ { if (total > 0) { pct = 100*hit/total; printf "%6.1f%% covered  %s  (%d/%d lines)\n", pct, file, hit, total } }
    ' target/coverage/lcov.info | sort -n | head -20
    echo '```'
    echo
  fi
  echo "## Hottest functions (CPU, self-time sample count)"
  echo
  echo '```'
  tail -n +2 profile/cpu-top.txt | head -20
  echo '```'
} > profile/bottleneck-report.md

echo
echo "Profile written to:"
echo "  profile/profile.json.gz    (interactive — samply load profile/profile.json.gz)"
echo "  profile/cpu-top.txt        (LLM/tool-ingestable)"
echo "  profile/bottleneck-report.md (combined coverage + hot-path summary; run scripts/coverage.sh first for the coverage section)"
echo
echo "For heap profiling: cargo run --release --features profiling -- search \"test query\""
echo "  (writes dhat-heap.json — view at https://nnethercote.github.io/dh_view/dh_view.html)"
