#!/usr/bin/env bash
# Copilot speed diagnosis (macOS / Linux). Usage: curl -s https://speed.instaconsult.me/speed-test.sh | bash
set -u
echo "== Copilot speed test =="
echo "Time:      $(date '+%Y-%m-%d %H:%M:%S %Z (UTC%z)')"
echo "Host:      $(uname -sm)"
curl -s --max-time 10 https://ipinfo.io/json | python3 -c '
import json,sys
d=json.load(sys.stdin)
ip=d.get("ip","?")
print("Public IP: " + ".".join(ip.split(".")[:3]) + ".x  (full: " + ip + ")")
print("ISP:       " + str(d.get("org","?")))
print("Location:  " + ", ".join(x for x in [d.get("city"),d.get("country")] if x))
' 2>/dev/null || echo "IP/ISP:    lookup failed"

echo
echo "-- Network (Cloudflare endpoints, same on every OS)"
down=$(curl -s -o /dev/null --max-time 30 -w '%{speed_download}' "https://speed.cloudflare.com/__down?bytes=25000000")
echo "Download:  $(awk -v b="$down" 'BEGIN{printf "%.1f Mbps", b*8/1e6}')"
tmp=$(mktemp); head -c 10000000 /dev/zero > "$tmp"
up=$(curl -s -o /dev/null --max-time 30 -w '%{speed_upload}' -X POST --data-binary @"$tmp" https://speed.cloudflare.com/__up)
rm -f "$tmp"
echo "Upload:    $(awk -v b="$up" 'BEGIN{printf "%.1f Mbps", b*8/1e6}')"
lat=$(for i in 1 2 3 4 5; do curl -s -o /dev/null -w '%{time_connect}\n' "https://speed.cloudflare.com/__down?bytes=0"; done | sort -n | awk '{a[NR]=$1} END{printf "%.0f", a[int((NR+1)/2)]*1000}')
echo "Latency:   ${lat} ms (median TCP connect, 5 tries)"

if command -v networkQuality >/dev/null 2>&1; then
  echo
  echo "-- macOS networkQuality (includes latency under load)"
  networkQuality -s 2>&1 | grep -iE "capacity|responsiveness|idle latency"
fi

echo
echo "-- Copilot API connection setup (median of 5)"
for h in api.githubcopilot.com api.individual.githubcopilot.com; do
  t=$(for i in 1 2 3 4 5; do curl -s -o /dev/null --max-time 10 -w '%{time_appconnect}\n' "https://$h/"; done | sort -n | awk '{a[NR]=$1} END{printf "%.2f", a[int((NR+1)/2)]}')
  echo "$h: ${t} s (TCP + TLS)"
done
echo
echo "Done. Paste this output back into the chat."
