#!/bin/zsh
# ╭──────────────────────────────────────────────────────────────╮
# │  WiFi Lab — terminal edition                                 │
# │  Deep Wi-Fi analysis for any Mac. Uses only built-in tools.  │
# ╰──────────────────────────────────────────────────────────────╯
# Usage: wifilab [command] [options]      (wifilab help for everything)

emulate -L zsh
[[ ${LC_ALL:-${LC_CTYPE:-$LANG}} == *UTF-8* ]] || export LC_ALL=en_US.UTF-8
setopt no_nomatch pipe_fail no_bg_nice no_notify no_monitor
zmodload zsh/mathfunc 2>/dev/null
zmodload zsh/datetime 2>/dev/null

VERSION="1.0"
DATA_DIR="${WIFILAB_HOME:-$HOME/.wifilab}"
SAVE_DIR="$DATA_DIR/scans"
HIST="$DATA_DIR/history.tsv"
TMP=$(mktemp -d -t wifilab) || exit 1
SUA="wifilab/1.0 (+speed test)"
UA="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130 Safari/537.36"
cleanup() { jobs -p 2>/dev/null | xargs kill 2>/dev/null; rm -rf "$TMP"; tput cnorm 2>/dev/null; }
trap cleanup EXIT
trap 'echo; exit 130' INT

# ───────────────────────────────── colors
if [[ -t 1 && -z "$NO_COLOR" && "$*" != *--no-color* ]]; then
  R=$'\e[0m'; B=$'\e[1m'; D=$'\e[2m'; CY=$'\e[38;5;51m'; VI=$'\e[38;5;141m'; GR=$'\e[38;5;84m'
  AM=$'\e[38;5;221m'; RD=$'\e[38;5;204m'; GY=$'\e[38;5;245m'; WH=$'\e[38;5;255m'
else R= B= D= CY= VI= GR= AM= RD= GY= WH=; fi

# ───────────────────────────────── helpers
num()    { [[ "$1" == <->(|.<->) || "$1" == -<->(|.<->) ]]; }
f0()     { num "$1" && printf "%.0f" "$1" || print -n "—"; }
f1()     { num "$1" && printf "%.1f" "$1" || print -n "—"; }
clampv() { local v=$1; (( v < 0 )) && v=0; (( v > 100 )) && v=100; printf "%.0f" $v; }
scol()   { local v=${1:-0}; num $v || { print -n $GY; return; }; (( v >= 80 )) && print -n $GR || { (( v >= 60 )) && print -n $CY || { (( v >= 40 )) && print -n $AM || print -n $RD; }; }; }
bar()    { # bar VALUE WIDTH
  local v=${1:-0} w=${2:-24} i full; num $v || v=0; full=$(( int(v * w / 100.0 + 0.5) ))
  local out=""; for ((i=0;i<w;i++)); do (( i < full )) && out+="█" || out+="░"; done
  print -n "$(scol $v)$out$R"; }
hr()     { print "${GY}${(l:62::─:)}${R}"; }
section(){ print; print "  ${B}${WH}$1${R}"; print "  ${GY}${(l:60::─:)}${R}"; }
kv()     { printf "  ${GY}%-20s${R} %s\n" "$1" "$2"; }
note()   { print "  ${GY}$1${R}"; }
spin()   { local pid=$1 msg=$2 s='⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏' i=0
  if [[ ! -t 1 ]]; then wait $pid 2>/dev/null; print "  ✓ $msg"; return; fi; tput civis 2>/dev/null
  while kill -0 $pid 2>/dev/null; do printf "\r  ${CY}%s${R} %s" "${s:$((i%10)):1}" "$msg"; sleep 0.1; ((i++)); done
  printf "\r  ${GR}✓${R} %s\n" "$msg"; tput cnorm 2>/dev/null; }
jget()   { plutil -extract "$2" raw -o - "$1" 2>/dev/null; }   # jget FILE key.path
fmt_time(){ local s=$1; (( s < 60 )) && { printf "%.0f s" $s; return; }; (( s < 3600 )) && { printf "%.0f min" $((s/60.0)); return; }; printf "%.1f h" $((s/3600.0)); }
commas() { printf "%.0f" $1 | sed -e :a -e 's/\(.*[0-9]\)\([0-9]\{3\}\)/\1,\2/;ta'; }
iso_now(){ strftime "%Y-%m-%d %H:%M:%S" $EPOCHSECONDS; }

# ───────────────────────────────── radio
wifi_iface() { networksetup -listallhardwareports 2>/dev/null | awk '/Hardware Port: Wi-Fi/{getline; print $2; exit}'; }

read_radio() {
  IFACE=$(wifi_iface); IFACE=${IFACE:-en0}
  system_profiler SPAirPortDataType 2>/dev/null > "$TMP/sp.txt"
  # current network + nearby networks, one line per radio: kind|channel|band|width|rssi|noise|phy|security|rate|mcs
  awk '
    function flush(){ if (have) print mode"|"ch"|"band"|"w"|"rs"|"no"|"phy"|"sec"|"rate"|"mcs; have=0; ch=band=w=rs=no=phy=sec=rate=mcs="" }
    { ind = match($0, /[^ ]/) - 1 }
    /Current Network Information:/ { flush(); mode="cur"; base=ind; next }
    /Other Local Wi-Fi Networks:/  { flush(); mode="near"; base=ind; next }
    mode == "" { next }
    ind <= base { flush(); mode=""; next }
    ind == base + 2 { flush(); have=1; next }
    /PHY Mode:/        { sub(/.*PHY Mode: /,""); phy=$0 }
    /Channel:/         { sub(/.*Channel: /,""); split($0,a,/[ (,)]+/); ch=a[1]; band=a[2]; w=a[3]; sub(/MHz/,"",w) }
    /Security:/        { sub(/.*Security: /,""); sec=$0 }
    /Signal \/ Noise:/ { sub(/.*Noise: /,""); gsub(/ dBm/,""); split($0,sn," / "); rs=sn[1]; no=sn[2] }
    /Transmit Rate:/   { sub(/.*Rate: /,""); rate=$0 }
    /MCS Index:/       { sub(/.*Index: /,""); mcs=$0 }
    END { flush() }
' "$TMP/sp.txt" > "$TMP/radios.txt"
  local line; line=$(grep -m1 '^cur|' "$TMP/radios.txt")
  IFS='|' read -r _ CH BAND WIDTH RSSI NOISE PHY SEC RATE MCS <<< "$line"
  CARD=$(awk -F': ' '/Card Type:/{print $2; exit}' "$TMP/sp.txt" | sed 's/  */ /g')
  PHYS=$(awk -F': ' '/Supported PHY Modes:/{print $2; exit}' "$TMP/sp.txt")
  COUNTRY=$(awk -F': ' '/Country Code:/{print $2; exit}' "$TMP/sp.txt")
  MYMAC=$(awk -F': ' '/MAC Address:/{print $2; exit}' "$TMP/sp.txt")
  SSID=$(ipconfig getsummary "$IFACE" 2>/dev/null | awk -F' : ' '/^ +SSID :/{print $2; exit}')
  [[ "$SSID" == *redacted* ]] && SSID=""
  SECDETAIL=$(ipconfig getsummary "$IFACE" 2>/dev/null | awk -F' : ' '/^ +Security :/{print $2; exit}')
  NEAR_COUNT=$(grep -c '^near|' "$TMP/radios.txt")
  CONNECTED=0; [[ -n "$CH" ]] && CONNECTED=1
  SNR=""; num "$RSSI" && num "$NOISE" && SNR=$(( RSSI - NOISE ))
}

sec_name() {
  local s=${(L)1}
  [[ $s == *wpa3*transition* || $s == *wpa2/wpa3* ]] && { print "WPA2/WPA3 mixed"; return; }
  [[ $s == *wpa3*enterprise* ]] && { print "WPA3-Enterprise"; return; }
  [[ $s == *wpa3* ]] && { print "WPA3-Personal"; return; }
  [[ $s == *wpa2*enterprise* ]] && { print "WPA2-Enterprise"; return; }
  [[ $s == *wpa2* ]] && { print "WPA2-Personal"; return; }
  [[ $s == *wpa* ]] && { print "WPA (old)"; return; }
  [[ $s == *wep* ]] && { print "WEP (broken!)"; return; }
  [[ $s == *none* || $s == *open* ]] && { print "Open (no password)"; return; }
  print "${1:-Unknown}"
}
rssi_q() { local r=$1; num $r || { print "—"; return; }; (( r >= -55 )) && print "${GR}Excellent${R}" || { (( r >= -65 )) && print "${CY}Good${R}" || { (( r >= -72 )) && print "${AM}Fair${R}" || print "${RD}Weak${R}"; }; }; }
freq_mhz() { local c=$1; num $c || return; (( c <= 13 )) && { print $(( 2407 + 5*c )); return; }; (( c == 14 )) && { print 2484; return; }; print $(( 5000 + 5*c )); }

# ───────────────────────────────── network
oui_vendor() {
  local m=${(L)1}; m=${m[1,8]}
  case $m in
    94:f3:92|00:09:0f|90:6c:ac|70:4c:a5) print "Fortinet";; 00:0b:86|24:de:c6) print "Aruba (HPE)";;
    00:18:0a|0c:8d:db|e0:55:3d) print "Cisco Meraki";; 74:83:c2|24:5a:4c|f0:9f:c2|b4:fb:e4) print "Ubiquiti";;
    *) [[ -n $m ]] && curl -s --max-time 4 "https://api.macvendors.com/$m" 2>/dev/null | grep -v errors | head -c 60;;
  esac
}
dns_provider() {
  case $1 in
    149.112.121.10|149.112.122.10) print "CIRA Canadian Shield (Protected)";; 149.112.121.20|149.112.122.20) print "CIRA Canadian Shield (Family)";;
    1.1.1.1|1.0.0.1) print "Cloudflare";; 1.1.1.3|1.0.0.3) print "Cloudflare for Families";; 8.8.8.8|8.8.4.4) print "Google Public DNS";;
    9.9.9.9|149.112.112.112) print "Quad9";; 208.67.222.222|208.67.220.220) print "Cisco OpenDNS / Umbrella";;
    185.228.168.*) print "CleanBrowsing";; 94.140.14.*) print "AdGuard DNS";;
  esac
}
ping_stats() { # ping_stats HOST COUNT INTERVAL -> "avg jitter loss min max"
  ping -c ${2:-10} -i ${3:-0.2} -t $(( ${2:-10} + 5 )) $1 2>/dev/null | awk -F'time=' '/time=/{split($2,a," "); t[n++]=a[1]}
    END{ if(!n){print "- - 100 - -"; exit}; s=0; j=0; mn=t[0]; mx=t[0]
      for(i=0;i<n;i++){s+=t[i]; if(t[i]<mn)mn=t[i]; if(t[i]>mx)mx=t[i]; if(i)j+=(t[i]>t[i-1]?t[i]-t[i-1]:t[i-1]-t[i])}
      printf "%.2f %.2f %.1f %.2f %.2f\n", s/n, (n>1?j/(n-1):0), 100*('"${2:-10}"'-n)/'"${2:-10}"', mn, mx }'
}

read_network() {
  ipconfig getpacket "$IFACE" 2>/dev/null > "$TMP/dhcp.txt"
  IP=$(awk '/^yiaddr/{print $3}' "$TMP/dhcp.txt"); [[ -z $IP || $IP == 0.0.0.0 ]] && IP=$(ipconfig getifaddr "$IFACE" 2>/dev/null)
  MASK=$(awk -F': ' '/subnet_mask/{print $2}' "$TMP/dhcp.txt")
  GW=$(awk -F'[{}]' '/^router/{split($2,a,","); print a[1]}' "$TMP/dhcp.txt"); [[ -z $GW ]] && GW=$(route -n get default 2>/dev/null | awk '/gateway/{print $2}')
  DHCPSRV=$(awk -F': ' '/server_identifier/{print $2}' "$TMP/dhcp.txt")
  RELAY=$(awk '/^giaddr/{print $3}' "$TMP/dhcp.txt"); [[ $RELAY == 0.0.0.0 ]] && RELAY=""
  local lt; lt=$(awk -F': ' '/lease_time/{print $2}' "$TMP/dhcp.txt"); LEASE=""; [[ -n $lt ]] && LEASE=$(( lt ))
  DOMAIN=$(awk -F': ' '/^domain_name \(/{print $2}' "$TMP/dhcp.txt")
  DNS=$(awk -F'[{}]' '/domain_name_server/{gsub(/ /,"",$2); print $2}' "$TMP/dhcp.txt")
  [[ -z $DNS ]] && DNS=$(scutil --dns 2>/dev/null | awk '/nameserver\[0\]/{print $3; exit}')
  DNSPROV=""; for d in ${(s:,:)DNS}; do DNSPROV=$(dns_provider $d); [[ -n $DNSPROV ]] && break; done

  # run slow probes in parallel
  ( curl -s --max-time 6 -A "$UA" https://ipinfo.io/json > "$TMP/ipinfo.json" ) &
  ( curl -s --max-time 6 -A "$UA" https://www.cloudflare.com/cdn-cgi/trace > "$TMP/cf.txt" ) &
  ( traceroute -n -w 1 -q 1 -m 18 1.1.1.1 2>/dev/null > "$TMP/trace.txt" ) &
  ( ping_stats 1.1.1.1 10 0.2 > "$TMP/inetping.txt" ) &
  ( [[ -n $GW ]] && ping_stats $GW 10 0.2 > "$TMP/gwping.txt" ) &
  ( for h in www.google.com www.wikipedia.org github.com; do
      iss=$(echo | openssl s_client -connect $h:443 -servername $h 2>/dev/null | openssl x509 -noout -issuer 2>/dev/null | sed 's/^issuer= *//')
      print -r -- "$h|$iss"; done > "$TMP/tls.txt" ) &
  ( for s in 8.8.8.8 1.1.1.1 9.9.9.9; do dig +time=2 +tries=1 +short @$s example.com A >/dev/null 2>&1 && print "$s ok" || print "$s blocked"; done > "$TMP/extdns.txt" ) &
  ( curl -s --max-time 4 https://api6.ipify.org > "$TMP/v6.txt" 2>/dev/null ) &
  ( curl -s --max-time 5 http://captive.apple.com/hotspot-detect.html | grep -q Success && print ok > "$TMP/captive.txt" || print portal > "$TMP/captive.txt" ) &
  wait

  PUBIP=$(jget "$TMP/ipinfo.json" ip); ORG=$(jget "$TMP/ipinfo.json" org); CITY=$(jget "$TMP/ipinfo.json" city)
  REGION=$(jget "$TMP/ipinfo.json" region); PHOST=$(jget "$TMP/ipinfo.json" hostname)
  [[ -z $PUBIP ]] && PUBIP=$(awk -F= '/^ip=/{print $2}' "$TMP/cf.txt")
  ISP=${ORG#AS<-> }
  COLO=$(awk -F= '/^colo=/{print $2}' "$TMP/cf.txt"); TLSV=$(awk -F= '/^tls=/{print $2}' "$TMP/cf.txt"); KEX=$(awk -F= '/^kex=/{print $2}' "$TMP/cf.txt")
  read IPING IJIT ILOSS _ _ < "$TMP/inetping.txt"
  GWPING=""; [[ -f "$TMP/gwping.txt" ]] && read GWPING GWJIT GWLOSS _ _ < "$TMP/gwping.txt"
  GWMAC=""; [[ -n $GW ]] && GWMAC=$(arp -n $GW 2>/dev/null | awk '{for(i=1;i<=NF;i++) if($i=="at") print $(i+1)}')
  GWVENDOR=""; [[ -n $GWMAC && $GWMAC != *incomplete* ]] && GWVENDOR=$(oui_vendor $GWMAC)
  IPV6=$(cat "$TMP/v6.txt" 2>/dev/null); [[ $IPV6 != *:* ]] && IPV6=""
  CAPTIVE=$(cat "$TMP/captive.txt")
  HOPS=$(grep -cE '^ *[0-9]+ ' "$TMP/trace.txt")
  INTERCEPT=""; while IFS='|' read -r h iss; do
    for v in fortinet fortigate securly lightspeed goguardian iboss zscaler "palo alto" sophos umbrella contentkeeper netsweeper smoothwall barracuda linewize; do
      [[ ${(L)iss} == *$v* ]] && INTERCEPT="$v"; done; done < "$TMP/tls.txt"
  EXTDNS_OK=$(grep -c ' ok' "$TMP/extdns.txt")
  FW=$(/usr/libexec/ApplicationFirewall/socketfilterfw --getglobalstate 2>/dev/null); [[ $FW == *enabled* ]] && MACFW=1 || MACFW=0
  ARPN=$(arp -an 2>/dev/null | grep -v incomplete | grep -vc 'ff:ff:ff')
  local first=$(( 16#${MYMAC[1,2]:-00} )); PRIVMAC=$(( (first & 2) ? 1 : 0 ))
}

# ───────────────────────────────── block checks
CATS=(
  "📱 Social media|tiktok.com instagram.com snapchat.com facebook.com x.com reddit.com"
  "💬 Chat|discord.com web.whatsapp.com telegram.org"
  "🎬 Video & music|youtube.com netflix.com twitch.tv spotify.com disneyplus.com"
  "🎮 Gaming|roblox.com store.steampowered.com epicgames.com minecraft.net poki.com chess.com"
  "🤖 AI tools|chatgpt.com claude.ai gemini.google.com perplexity.ai"
  "🕳️  VPNs & proxies|nordvpn.com protonvpn.com torproject.org expressvpn.com"
  "📚 School & learning|wikipedia.org khanacademy.org github.com stackoverflow.com desmos.com"
  "🛒 Shopping|amazon.ca ebay.com aliexpress.com"
  "🚫 Adult/gambling/piracy|pornhub.com bet365.com thepiratebay.org"
)
check_site() { # -> status|how
  local d=$1 ip code rc body
  ip=$(dig +short +time=3 +tries=1 $d A 2>/dev/null | grep -E '^[0-9.]+$' | head -1)
  [[ -z $ip ]] && { print "blocked|DNS gave no answer"; return; }
  case $ip in
    208.91.112.55) print "blocked|DNS redirected to FortiGuard block page"; return;;
    146.112.61.10*) print "blocked|DNS redirected to Cisco Umbrella block page"; return;;
    0.0.0.0|127.0.0.1) print "blocked|DNS sinkholed"; return;;
  esac
  body="$TMP/b_$d.html"
  code=$(curl -s -L --max-time 7 -A "$UA" -o "$body" -w '%{http_code}' "https://$d/" 2>/dev/null); rc=$?
  case $rc in
    0) if grep -qiE 'fortiguard|web page blocked|securly|lightspeed|goguardian|iboss|contentkeeper|netsweeper|smoothwall|this site has been blocked|linewize' "$body" 2>/dev/null
       then print "blocked|Block page served"; else print "open|Loaded (HTTP $code)"; fi;;
    28) print "blocked|Silently dropped (filtered by site name)";;
    35|51|58|60|90) print "blocked|Certificate swapped (firewall block page)";;
    7|56|52) print "blocked|Connection reset by firewall";;
    6) print "blocked|Name lookup failed";;
    *) print "error|curl error $rc";;
  esac
}
run_blocks() {
  local c name doms d
  mkdir -p "$TMP/blk"
  for c in $CATS; do for d in ${=c#*|}; do ( check_site $d > "$TMP/blk/$d" ) & done; done
  wait
  BLOCKED=0; TESTED=0; OPENNA=0; TOTALNA=0
  for c in $CATS; do name=${c%%|*}; for d in ${=c#*|}; do
    local r=$(cat "$TMP/blk/$d" 2>/dev/null); ((TESTED++)); [[ $r == blocked* ]] && ((BLOCKED++))
    if [[ $name != *Adult* && $r != error* ]]; then ((TOTALNA++)); [[ $r == open* ]] && ((OPENNA++)); fi
  done; done
  FREEDOM=""; (( TOTALNA )) && FREEDOM=$(( 100.0 * OPENNA / TOTALNA ))
}

PORTS=("22:SSH" "25:Email sending" "53:DNS (TCP)" "80:Web (HTTP)" "123:Time (NTP)" "443:Secure web" "993:Email (IMAPS)" "1194:OpenVPN" "3389:Remote Desktop" "5222:Chat (XMPP)" "8080:Alt web" "25565:Minecraft Java" "27015:Steam games" "3074:Xbox Live / CoD" "51820:WireGuard")
run_ports() { mkdir -p "$TMP/ports"; local p; for p in $PORTS; do ( nc -z -G 3 -w 3 portquiz.net ${p%%:*} >/dev/null 2>&1 && print open > "$TMP/ports/${p%%:*}" || print closed > "$TMP/ports/${p%%:*}" ) & done; wait; }

# ───────────────────────────────── speed test
iface_bytes() { netstat -ibn -I "$IFACE" 2>/dev/null | awk '$3 ~ /Link/ {print $7, $10; exit}'; }
speed_phase() { # speed_phase down|up SECONDS STREAMS -> sets PHASE_MBPS, prints live meter
  local kind=$1 secs=$2 streams=$3 i
  local -a pids
  if [[ $kind == down ]]; then
    local url="" u got; DL_SERVER=""
    # use the first server that actually delivers data (Cloudflare rate-limits heavy testers)
    for u in "https://speed.cloudflare.com/__down?bytes=25000000|Cloudflare ${COLO:-}" "https://ash-speed.hetzner.com/100MB.bin|Hetzner (Virginia)" \
             "https://proof.ovh.ca/files/100Mb.dat|OVH Canada" "https://fsn1-speed.hetzner.com/100MB.bin|Hetzner (Germany)"; do
      got=$(curl -s -o /dev/null -w '%{http_code} %{size_download}' --max-time 3 -r 0-300000 -A "$SUA" "${u%%|*}")
      [[ ${got%% *} == 20? && ${got#* } -ge 100000 ]] && { url=${u%%|*}; DL_SERVER=${u#*|}; break; }
    done
    [[ -z $url ]] && { print "  ${RD}No speed-test server reachable from this network.${R}"; PHASE_MBPS=0; PHASE_BYTES=0; SERIES=(); return; }
    for ((i=0;i<streams;i++)); do ( while [[ ! -f "$TMP/stop_$kind" ]]; do curl -s -o /dev/null --max-time 12 -A "$SUA" "$url"; done ) & pids+=($!); done
  else
    [[ -f "$TMP/blob" ]] || head -c 20000000 /dev/urandom > "$TMP/blob"
    for ((i=0;i<streams;i++)); do ( while [[ ! -f "$TMP/stop_$kind" ]]; do curl -s -o /dev/null --max-time 12 -A "$SUA" -X POST -H "Content-Type: application/octet-stream" --data-binary @"$TMP/blob" "https://speed.cloudflare.com/__up"; done ) & pids+=($!); done
  fi
  ( ping_stats 1.1.1.1 $(( int(secs / 0.35) - 3 )) 0.35 > "$TMP/loaded_$kind.txt" ) & local pp=$!
  local t0=$EPOCHREALTIME last_t=$EPOCHREALTIME b0 b last_b warm_b="" warm_t="" now inst peak=0 col
  read -r bi bo <<< "$(iface_bytes)"; [[ $kind == down ]] && b0=$bi || b0=$bo; last_b=$b0
  local label="Download ↓"; [[ $kind == up ]] && label="Upload ↑  "
  tput civis 2>/dev/null
  SERIES=()
  while (( EPOCHREALTIME - t0 < secs )); do
    sleep 0.25; now=$EPOCHREALTIME
    read -r bi bo <<< "$(iface_bytes)"; [[ $kind == down ]] && b=$bi || b=$bo
    inst=$(( (b - last_b) * 8.0 / (now - last_t) / 1e6 )); last_b=$b; last_t=$now
    (( inst > peak )) && peak=$inst; SERIES+=($inst)
    if [[ -z $warm_b ]] && (( now - t0 > 2.0 )); then warm_b=$b; warm_t=$now; fi
    local pct=$(( log10(inst > 1 ? inst : 1) / 3.0 * 100 ))
    local left=$(( secs - (now - t0) )); (( left < 0 )) && left=0
    printf "\r  ${B}%s${R}  %s  ${B}${CY}%7.1f${R} Mbps  ${GY}%2.0fs${R} " "$label" "$(bar $pct 28)" $inst $left
  done
  touch "$TMP/stop_$kind"; for p in $pids; do pkill -P $p 2>/dev/null; done; wait $pids 2>/dev/null
  local end_t=$EPOCHREALTIME
  read -r bi bo <<< "$(iface_bytes)"; [[ $kind == down ]] && b=$bi || b=$bo
  PHASE_MBPS=$(( (b - ${warm_b:-$b0}) * 8.0 / (end_t - ${warm_t:-$t0}) / 1e6 ))
  PHASE_BYTES=$(( b - b0 ))
  wait $pp 2>/dev/null
  printf "\r  ${B}%s${R}  %s  ${B}${GR}%7.1f${R} Mbps  ${GY}done${R}   \n" "$label" "$(bar $(( log10(PHASE_MBPS > 1 ? PHASE_MBPS : 1) / 3.0 * 100 )) 28)" $PHASE_MBPS
  tput cnorm 2>/dev/null
}
sparkline() { local -a v=("$@"); local mx=1 s="" x ch=(▁ ▂ ▃ ▄ ▅ ▆ ▇ █); for x in $v; do (( x > mx )) && mx=$x; done
  for x in $v; do s+=${ch[$(( int(x / mx * 7) + 1 ))]}; done; print -n "$s"; }

run_speed() {
  section "⚡ SPEED TEST  ${GY}(~300–600 MB of data)${R}"
  printf "  ${B}Ping      ${R}  measuring…"
  read SPING SJIT SLOSS _ _ <<< "$(ping_stats 1.1.1.1 20 0.2)"
  printf "\r  ${B}Ping      ${R}  ${B}${CY}%s ms${R}  ${GY}jitter %s ms · loss %s%%${R}          \n" "$(f1 $SPING)" "$(f1 $SJIT)" "$(f1 $SLOSS)"
  speed_phase down 10 6; DOWN=$PHASE_MBPS; DBYTES=$PHASE_BYTES; DSERIES=($SERIES)
  speed_phase up 8 4; UP=$PHASE_MBPS; UBYTES=$PHASE_BYTES; USERIES=($SERIES)
  read DLPING _ _ _ _ < "$TMP/loaded_down.txt"; read ULPING _ _ _ _ < "$TMP/loaded_up.txt"
  BLOAT=""; if num $SPING && num $DLPING; then local mxl=$DLPING; num $ULPING && (( ULPING > mxl )) && mxl=$ULPING; BLOAT=$(( mxl - SPING )); (( BLOAT < 0 )) && BLOAT=0; fi
  SPEED_AT=$(iso_now); SPEED_DONE=1
}
bloat_grade() { local b=$1; num $b || { print "—"; return; }; (( b < 5 )) && print "A+" || { (( b < 30 )) && print A || { (( b < 60 )) && print B || { (( b < 200 )) && print C || { (( b < 400 )) && print D || print F; }; }; }; }; }

# ───────────────────────────────── scores
compute_scores() {
  S_SIG=""; S_SPD=""; S_LAT=""; S_STAB=""
  if num "$SNR"; then S_SIG=$(clampv $(( (SNR - 10) / 32.0 * 100 ))); elif num "$RSSI"; then S_SIG=$(clampv $(( (RSSI + 88) / 38.0 * 100 ))); fi
  if [[ -n $SPEED_DONE ]] && num $DOWN; then
    local d=$(clampv $(( 100 * log10(DOWN > 1 ? DOWN : 1) / log10(500) ))) u=$(clampv $(( 100 * log10(UP > 1 ? UP : 1) / log10(200) )))
    S_SPD=$(clampv $(( 0.7 * d + 0.3 * u )))
  fi
  local lat=${SPING:-$IPING}; num $lat && S_LAT=$(clampv $(( 100 - (lat - 8) * 1.1 )))
  num "$BLOAT" && S_STAB=$(clampv $(( 100 - BLOAT * 0.35 - ${SJIT:-0} * 2 - ${SLOSS:-0} * 10 )))
  local tot=0 ws=0
  num "$S_SIG"  && (( tot += S_SIG * 0.25, ws += 0.25 ))
  num "$S_SPD"  && (( tot += S_SPD * 0.35, ws += 0.35 ))
  num "$S_LAT"  && (( tot += S_LAT * 0.2, ws += 0.2 ))
  num "$S_STAB" && (( tot += S_STAB * 0.2, ws += 0.2 ))
  SCORE=""; (( ws > 0 )) && SCORE=$(printf "%.0f" $(( tot / ws )))
  # security
  SECSCORE=100; local sn=$(sec_name "$SEC")
  case $sn in Open*) (( SECSCORE -= 50 ));; WEP*) (( SECSCORE -= 45 ));; "WPA (old)") (( SECSCORE -= 30 ));; WPA2-Personal) (( SECSCORE -= 10 ));; *mixed) (( SECSCORE -= 5 ));; esac
  [[ -n $INTERCEPT ]] && (( SECSCORE -= 25 )); (( PRIVMAC )) || (( SECSCORE -= 5 )); (( MACFW )) || (( SECSCORE -= 10 ))
  (( SECSCORE < 0 )) && SECSCORE=0
  VERDICT="Scanned"; num "$SCORE" && { (( SCORE >= 85 )) && VERDICT="Excellent Wi-Fi 🚀" || { (( SCORE >= 70 )) && VERDICT="Great Wi-Fi 👍" || { (( SCORE >= 55 )) && VERDICT="Decent Wi-Fi 🙂" || { (( SCORE >= 40 )) && VERDICT="Mediocre Wi-Fi 😐" || VERDICT="Rough Wi-Fi 😬"; }; }; }; }
}

# ───────────────────────────────── report sections
show_header() {
  print
  print "  ${B}${CY}📡 WiFi Lab${R}  ${GY}terminal edition v$VERSION${R}"
  print "  ${GY}$(iso_now) · $(sw_vers -productName 2>/dev/null) $(sw_vers -productVersion 2>/dev/null)${R}"
}
show_score() {
  print
  local name=${NETNAME:-${SSID:-this network}}
  print "  ${B}$(scol ${SCORE:-0})╭───────╮${R}"
  printf "  ${B}$(scol ${SCORE:-0})│  %3s  │${R}  ${B}%s${R}\n" "${SCORE:-—}" "$VERDICT"
  printf "  ${B}$(scol ${SCORE:-0})╰───────╯${R}  ${GY}%s · %s · %s ch %s · %s${R}\n" "$name" "${PHY:-?}" "${BAND:-?}" "${CH:-?}" "$(sec_name "$SEC")"
  print "  ${GY}WIFI SCORE${R}"
  print
  local k v
  for k v in Signal "$S_SIG" Speed "$S_SPD" Latency "$S_LAT" Stability "$S_STAB" Security "$SECSCORE" Freedom "$( [[ -n $FREEDOM ]] && printf %.0f $FREEDOM)"; do
    num "$v" && printf "  ${GY}%-10s${R} %s ${B}$(scol $v)%3s${R}\n" $k "$(bar $v 30)" $v
  done
  [[ -z $SPEED_DONE && -z $NOSPEED_NOTE ]] && note "Run without --no-speed for a complete score."
}
show_speed_summary() {
  [[ -z $SPEED_DONE ]] && return
  section "⚡ SPEED RESULTS ${GY}download server: ${DL_SERVER:-Cloudflare}${R}"
  kv "Download" "${B}${CY}$(f0 $DOWN) Mbps${R}"
  kv "Upload" "${B}${GR}$(f0 $UP) Mbps${R}"
  kv "Ping / jitter / loss" "$(f1 $SPING) ms / $(f1 $SJIT) ms / $(f1 $SLOSS)%"
  kv "Ping under load" "$(f1 $DLPING) ms ↓   $(f1 $ULPING) ms ↑"
  kv "Bufferbloat" "${B}$(bloat_grade $BLOAT)${R} ${GY}(+$(f0 $BLOAT) ms when busy)${R}"
  (( ${#DSERIES} )) && kv "Throughput" "${CY}$(sparkline $DSERIES)${R}${GR}$(sparkline $USERIES)${R}"
  print
  local ok lat=${SPING:-99} jit=${SJIT:-0} b=${BLOAT:-0}
  act() { (( $2 )) && print "  ${GR}●${R} $1 ${GY}$3${R}" || print "  ${RD}●${R} $1 ${GY}$3${R}"; }
  local n4k=$(( int(DOWN / 25) ))
  act "📺 4K streaming" $(( DOWN >= 25 )) "$n4k stream$( (( n4k == 1 )) || print -n s) at once"
  act "🎥 HD video calls" $(( UP >= 4 && lat < 150 )) "$(( int((DOWN < UP ? DOWN : UP) / 4) )) at once"
  if (( lat < 40 && jit < 10 && b < 30 )); then act "🎯 Competitive gaming" 1 "low ping & stable"
  elif (( lat < 40 )); then act "🎯 Competitive gaming" 0 "good ping, but spikes when the network is busy"
  else act "🎯 Competitive gaming" 0 "ping too high"; fi
  act "☁️  Cloud gaming" $(( DOWN >= 35 && lat < 40 )) "needs 35 Mbps + <40 ms"
  act "💾 100 GB game download" 1 "$(fmt_time $(( 100000 / (DOWN / 8.0) )))"
  act "📤 Upload a 1 GB video" 1 "$(fmt_time $(( 1000 / ((UP > 0.1 ? UP : 0.1) / 8.0) )))"
}
show_radio() {
  section "📶 RADIO & SIGNAL"
  (( CONNECTED )) || { note "Not connected to Wi-Fi."; return; }
  kv "Network name" "${SSID:-${NETNAME:-${GY}hidden by macOS (no Location access)${R}}}"
  kv "Signal" "$RSSI dBm  $(rssi_q $RSSI)"
  kv "Noise floor" "${NOISE:-—} dBm"
  kv "SNR" "${SNR:-—} dB ${GY}(40+ is fantastic)${R}"
  local gen=""; [[ $PHY == *ax* ]] && gen="Wi-Fi 6"; [[ $PHY == *be* ]] && gen="Wi-Fi 7"; [[ -z $gen && $PHY == *ac* ]] && gen="Wi-Fi 5"; [[ -z $gen && $PHY == *n* ]] && gen="Wi-Fi 4"
  kv "Standard" "$PHY ${GY}$gen${R}"
  kv "Band / channel" "$BAND · channel $CH ${GY}($(freq_mhz $CH) MHz)${R}"
  kv "Channel width" "${WIDTH:-—} MHz"
  kv "Link rate" "${RATE:-—} Mbps ${GY}MCS ${MCS:-—}${R}"
  kv "Security" "$(sec_name "$SEC") ${GY}${SECDETAIL:+(connected via $SECDETAIL)}${R}"
  kv "Your Wi-Fi MAC" "$MYMAC ${GY}$( (( PRIVMAC )) && print randomized/private || print hardware)${R}"
  kv "Wi-Fi chip" "${CARD:-—}"
  kv "Country code" "${COUNTRY:-—}"
}
show_airwaves() {
  section "🌐 AIRWAVES ${GY}$(( NEAR_COUNT + 1 )) radios heard${R}"
  awk -F'|' '{c[$2]++; b[$2]=$3} END{for(k in c) print k, c[k], b[k]}' "$TMP/radios.txt" | sort -n | while read ch cnt bd; do
    local mark=""; [[ $ch == $CH ]] && mark=" ${CY}★ you${R}"
    printf "  ${GY}ch %-4s %-5s${R} %s ${B}%s${R}%s\n" $ch $bd "${VI}${(l:$((cnt*2))::█:)}${R}" $cnt "$mark"
  done
  local same=$(grep -c "^near|$CH|" "$TMP/radios.txt")
  (( same > 2 )) && note "$same other radios share your channel: almost certainly one managed mesh of access points."
}
show_nerd() {
  section "🤓 THE NERDY STUFF"
  kv "Local IP" "$IP"
  kv "Subnet mask" "${MASK:-—}"
  kv "Gateway" "${GW:-—} ${GY}${GWVENDOR:+made by $GWVENDOR}${R}"
  kv "Gateway ping" "$(f1 $GWPING) ms ${GY}jitter $(f1 $GWJIT) · loss $(f1 $GWLOSS)%${R}"
  kv "DHCP server" "${DHCPSRV:-—} ${GY}${RELAY:+(relayed via $RELAY)}${R}"
  [[ -n $LEASE ]] && kv "Lease time" "$(printf %.1f $(( LEASE / 3600.0 ))) h"
  kv "Search domain" "${DOMAIN:-—}"
  kv "DNS servers" "${DNS:-—} ${GY}${DNSPROV}${R}"
  kv "Public IP" "${PUBIP:-—} ${GY}${PHOST}${R}"
  kv "ISP" "${ISP:-—} ${GY}${CITY:+$CITY, }${REGION}${R}"
  kv "Cloudflare edge" "${COLO:-—}"
  kv "TLS / key exchange" "${TLSV:-—} / ${KEX:-—}"
  kv "IPv6" "${IPV6:-${GY}not available${R}}"
  kv "Internet ping" "$(f1 $IPING) ms ${GY}to 1.1.1.1${R}"
  kv "ARP neighbours" "$ARPN ${GY}(devices your Mac talked to; passive)${R}"
  kv "Captive portal" "$([[ $CAPTIVE == ok ]] && print none || print 'login page present')"
  print; print -n "  ${GY}Route:${R} ${GY}you${R}"
  awk -v gy="$GY" -v r="$R" '/^ *[0-9]+ /{ip=$2; ms=$3; if(ip=="*"){ms=""} printf " → %s%s", ip, (ms!=""? " " gy "(" ms "ms)" r:"") }' "$TMP/trace.txt"; print " → 🌍"
}
show_security() {
  section "🛡️  SECURITY  $(scol $SECSCORE)${B}$SECSCORE/100${R}"
  local sn=$(sec_name "$SEC")
  case $sn in
    Open*) print "  🔓 ${AM}Encryption: $sn${R}\n     ${GY}Anyone nearby can read unencrypted traffic. Stick to HTTPS and avoid logins.${R}";;
    *mixed) print "  🔐 Encryption: $sn\n     ${GY}WPA3 for new devices, WPA2 for old ones.${R}";;
    *Enterprise) print "  🔐 Encryption: $sn\n     ${GY}Everyone logs in with their own account: the gold standard.${R}";;
    *) print "  🔐 Encryption: $sn\n     ${GY}Everyone shares one password; anyone with it is on the same network as you.${R}";;
  esac
  [[ -n $INTERCEPT ]] && print "  👁️  ${AM}HTTPS is being inspected ($INTERCEPT)${R}\n     ${GY}The firewall swaps certificates to read encrypted traffic.${R}" \
                      || print "  ✅ HTTPS is not being decrypted\n     ${GY}Real certificates reached you; the network sees site names, not contents.${R}"
  (( PRIVMAC )) && print "  🎭 Private Wi-Fi address is ON" || print "  🏷️  ${AM}Using your real hardware MAC${R}\n     ${GY}Turn on Private Wi-Fi Address in Wi-Fi settings.${R}"
  (( MACFW )) && print "  🧱 macOS firewall ON" || print "  ⚠️  ${AM}macOS firewall OFF${R}\n     ${GY}Turn it on: System Settings → Network → Firewall.${R}"
  [[ -n $DNSPROV ]] && print "  🧯 Filtered DNS: $DNSPROV"
  (( EXTDNS_OK == 0 )) && print "  🔒 DNS is locked to the network's own servers" || print "  🌍 Outside DNS servers reachable"
  [[ $CAPTIVE != ok ]] && print "  🚪 ${AM}Captive portal detected: log in through the network's web page${R}"
  [[ -z $IPV6 ]] && print "  6️⃣  No IPv6 ${GY}(IPv4 only, not a security issue)${R}"
}
show_blocks() {
  section "🚧 WHAT'S BLOCKED  ${GY}$BLOCKED of $TESTED test sites${R}${FREEDOM:+  · Freedom $(printf %.0f $FREEDOM)%}"
  local c name d r st how shown tag nb nt
  for c in $CATS; do name=${c%%|*}; nb=0; nt=0
    for d in ${=c#*|}; do ((nt++)); [[ $(cat "$TMP/blk/$d") == blocked* ]] && ((nb++)); done
    (( nb == 0 )) && tag="${GR}open${R}" || { (( nb == nt )) && tag="${RD}blocked${R}" || tag="${AM}$nb/$nt blocked${R}"; }
    print "  ${B}$name${R}  $tag"
    for d in ${=c#*|}; do r=$(cat "$TMP/blk/$d"); st=${r%%|*}; how=${r#*|}; shown=$d; [[ $d == pornhub.com ]] && shown="p*****.com"
      [[ $st == open ]] && printf "     ${GR}✓${R} %-24s ${GY}%s${R}\n" $shown "$how" || printf "     ${RD}✗${R} %-24s ${GY}%s${R}\n" $shown "$how"
    done
  done
}
show_ports() {
  section "🚪 OPEN DOORS ${GY}(outgoing ports the firewall allows)${R}"
  local p line="" i=0 st cell
  for p in $PORTS; do st=$(cat "$TMP/ports/${p%%:*}" 2>/dev/null)
    [[ $st == open ]] && cell="${GR}●${R} ${(r:6:)${p%%:*}}${GY}${(r:16:)${p#*:}}${R}" || cell="${RD}●${R} ${(r:6:)${p%%:*}}${GY}${(r:16:)${p#*:}}${R}"
    line+="  $cell"; ((i++)); (( i % 3 == 0 )) && { print "$line"; line=""; }
  done; [[ -n $line ]] && print "$line"
}
show_insights() {
  section "🧠 INSIGHTS"
  local s=${SNR:-$(( RSSI + 95 ))}
  if (( CONNECTED )); then
    local q="${(L)$(rssi_q $RSSI | sed 's/\x1b\[[0-9;]*m//g')}"
    print "  • ${B}Signal is $q${R}: $RSSI dBm${SNR:+ with $SNR dB above the noise}. $( (( s >= 35 )) && print 'Enough for the fanciest modulation your card supports.' || { (( s >= 25 )) && print 'Solid, but moving closer to an access point would unlock faster rates.' || print 'Near the edge of coverage. Move closer to an access point.'; })"
    [[ $WIDTH == 20 && $BAND == 5GHz ]] && print "  • ${B}Narrow 20 MHz channels${R}: built for lots of devices (capacity) rather than raw speed per device."
    [[ $BAND == 2GHz ]] && print "  • ${B}You're on 2.4 GHz${R}: longer range but slower and crowded. Prefer 5 GHz if available."
  fi
  if [[ -n $SPEED_DONE ]]; then
    local eff=""; num $RATE && eff=$(( DOWN / RATE * 100 ))
    print "  • ${B}Real-world speed $(f0 $DOWN)↓ / $(f0 $UP)↑ Mbps${R}.${eff:+ That's $(f0 $eff)% of your $RATE Mbps radio link (60–70% is normal).}$( (( UP > DOWN * 0.6 )) && print ' Symmetric upload usually means fiber.')"
    print "  • ${B}Bufferbloat $(bloat_grade $BLOAT)${R}: ping rises ~$(f0 $BLOAT) ms when the line is busy. $( (( BLOAT > 30 )) && print 'Expect lag spikes in games when others download.' || print 'Games and calls should stay smooth.')"
  fi
  if [[ -n $TESTED ]] && (( TESTED )); then
    if (( BLOCKED )); then
      local cats=() c d; for c in $CATS; do for d in ${=c#*|}; do [[ $(cat "$TMP/blk/$d") == blocked* ]] && { local cn=${${c%%|*}#* }; cats+=("${cn#"${cn%%[! ]*}"}"); break; }; done; done
      print "  • ${B}Filtering is active${R} on ${#cats} categories: ${(j:, :)cats}."
    else print "  • ${B}No content filtering detected${R}: every test site loaded."; fi
  fi
  (( EXTDNS_OK == 0 )) && print "  • ${B}DNS is locked down${R}: lookups to Google, Cloudflare and Quad9 are blocked${DNSPROV:+; everything goes through $DNSPROV}."
  num $GWPING && print "  • ${B}Local hop latency $(f1 $GWPING) ms${R} to the gateway. $( (( GWPING < 5 )) && print 'Very clean Wi-Fi.' || { (( GWPING < 15 )) && print 'Normal for a busy network.' || print 'High: the Wi-Fi is congested right now.'; })"
  [[ -z $IPV6 ]] && print "  • ${B}No IPv6${R}: everyone shares one public IPv4 address (NAT)."
}
show_facts() {
  section "🤯 FUN FACTS"
  local f=0
  fact() { ((f++)); print "  $1  $2"; }
  if (( CONNECTED )) && num $RSSI; then
    local nw=$(( 10 ** (RSSI / 10.0) * 1e6 ))
    fact "🔬" "Your laptop receives about ${B}${CY}$(printf %.3g $nw) nanowatts${R} of radio power: roughly ${B}1 in $(commas $(( 100 / (nw * 1e-6) )))${R} of what a 100 mW access point sends."
    local fm=$(freq_mhz $CH)
    if num $fm; then
      local dist=$(( 10 ** ((20 - RSSI - 20 * log10(fm) + 27.55) / 20.0) ))
      fact "📏" "With no walls, physics puts the access point about ${B}${CY}$(printf %.0f $dist) m${R} away (free-space path loss)."
      local wl=$(( 299792458.0 / (fm * 1e6) * 100 ))
      fact "🌊" "Channel $CH vibrates ${B}${CY}$(printf %.2f $((fm/1000.0))) billion times a second${R}; each wave is ${B}$(printf %.1f $wl) cm${R} long."
    fi
    if num $NOISE; then
      local w=${WIDTH:-20}; local ktb=$(( -174 + 10 * log10(w * 1e6) ))
      fact "🌡️ " "Noise is $NOISE dBm. Pure thermal noise for $w MHz is $(printf %.0f $ktb) dBm, so your room is only ${B}${CY}$(printf %.0f $((NOISE - ktb))) dB${R} above the physics floor."
      local sh=$(( w * log2(1 + 10 ** (SNR / 10.0)) ))
      fact "🧮" "Shannon's 1948 limit for $w MHz at $SNR dB SNR is ${B}${CY}$(printf %.0f $sh) Mbps${R} per antenna stream. Your link rate is ${RATE:-?} Mbps$(num $RATE && printf ' (%.0f%% of the limit)' $(( RATE / sh * 100 )))."
    fi
    (( CH >= 52 && CH <= 144 )) && fact "📡" "Channel $CH is a ${B}DFS channel${R}: it shares airspace with weather & airport radar, and must jump channels within 10 s if radar appears."
    if num $MCS; then local -A Q=(0 BPSK 1 QPSK 2 QPSK 3 16-QAM 4 16-QAM 5 64-QAM 6 64-QAM 7 64-QAM 8 256-QAM 9 256-QAM 10 1024-QAM 11 1024-QAM 12 4096-QAM 13 4096-QAM)
      local -A BITS=(BPSK 1 QPSK 2 16-QAM 4 64-QAM 6 256-QAM 8 1024-QAM 10 4096-QAM 12); local q=${Q[$MCS]}
      [[ -n $q ]] && fact "🎛️ " "MCS $MCS = ${B}$q${R}: each radio symbol is one of ${B}$(( 2 ** BITS[$q] ))${R} shapes, carrying ${BITS[$q]} bits."
    fi
  fi
  if [[ -n $MASK ]]; then local bits=0 o; for o in ${(s:.:)MASK}; do while (( o )); do (( bits += o & 1, o >>= 1 )); done; done
    fact "🏟️ " "Your subnet is a ${B}/$bits${R}: room for ${B}$(commas $(( 2 ** (32 - bits) - 2 )))${R} devices."; fi
  num $LEASE && fact "⏳" "The network rented you ${B}$IP${R} for ${B}$(( LEASE / 3600 )) hours${R}."
  [[ -n $RELAY && -n $DHCPSRV && $RELAY != $DHCPSRV ]] && fact "📮" "Your address came from a server at ${B}$DHCPSRV${R}, relayed by $RELAY: a big, centrally managed network."
  [[ -n $GWVENDOR ]] && fact "🏭" "The gateway hardware is made by ${B}$GWVENDOR${R}."
  local lat=${SPING:-$IPING}; num $lat && fact "⚡" "A round trip to Cloudflare takes ${B}$(f1 $lat) ms${R}. Light in fiber could cover ${B}$(commas $(( lat / 2 * 200 ))) km${R} each way in that time; the server is at ${B}${COLO:-?}${R}."
  [[ -n $SPEED_DONE ]] && fact "🎮" "At $(f0 $DOWN) Mbps: a ${B}100 GB game in $(fmt_time $(( 100000 / (DOWN / 8.0) )))${R}, a 4 MB song in ${B}$(printf %.0f $(( 4 / (DOWN / 8.0) * 1000 ))) ms${R}."
  [[ -n $SPEED_DONE ]] && fact "📦" "This speed test moved ${B}$(printf %.0f $(( (DBYTES + UBYTES) / 1e6 ))) MB${R} in ~20 seconds."
  [[ -n $ISP ]] && fact "🏙️ " "The internet sees you as ${B}$PUBIP${R}, owned by ${B}$ISP${R}${CITY:+ in $CITY}. Everyone on this Wi-Fi shares it."
  (( HOPS )) && fact "🛰️ " "Your packets reach Cloudflare in ${B}$HOPS hops${R}, router to router like a relay baton."
  (( f == 0 )) && note "Connect to Wi-Fi for fun facts."
}

# ───────────────────────────────── saving & history
mkdir -p "$SAVE_DIR"
[[ -f $HIST ]] || print "id\tscanned_at\tname\tssid\tscore\tdown\tup\tping\trssi\tsecurity\tblocked\ttested\tisp" > "$HIST"
strip_ansi() { sed $'s/\e\\[[0-9;]*m//g'; }

choose_name() { # sets SAVE_NAME, SAVE_SSID
  local guess=${SSID:-}
  print; print "  ${B}💾 Save this Wi-Fi${R}  ${GY}scanned $SCANNED_AT${R}"
  print "  ${CY}1${R}) Use the network's Wi-Fi name ${GY}${SSID:+(detected: $SSID)}${R}"
  print "  ${CY}2${R}) Use a custom name ${GY}(e.g. School library, Grandma's house)${R}"
  local ch; read -r "ch?  Choose 1 or 2 [1]: "; ch=${ch:-1}
  if [[ $ch == 2 ]]; then
    read -r "SAVE_NAME?  Custom name: "
    [[ -z $SSID ]] && read -r "SAVE_SSID?  Wi-Fi name too? (optional, Enter to skip): " || SAVE_SSID=$SSID
  else
    if [[ -n $SSID ]]; then SAVE_SSID=$SSID
    else
      note "macOS hides the current Wi-Fi name from apps. Recent networks your Mac knows:"
      local -a known=("${(@f)$(networksetup -listpreferredwirelessnetworks $IFACE 2>/dev/null | tail -n +2 | sed 's/^[[:space:]]*//' | head -12)}")
      local i=1 k; for k in $known; do printf "     ${CY}%2d${R}) %s\n" $i "$k"; ((i++)); done
      local pick; read -r "pick?  Type a number or the Wi-Fi name: "
      [[ $pick == <-> && $pick -ge 1 && $pick -le ${#known} ]] && SAVE_SSID=${known[$pick]} || SAVE_SSID=$pick
    fi
    SAVE_NAME=$SAVE_SSID
  fi
  SAVE_NAME=${SAVE_NAME:-Unnamed Wi-Fi}; SAVE_NAME=${SAVE_NAME//$'\t'/ }; SAVE_SSID=${SAVE_SSID//$'\t'/ }
  NAME_SOURCE=network; [[ $ch == 2 ]] && NAME_SOURCE=custom
}
save_scan() { # save_scan REPORTFILE [name]
  if [[ -n $1 && -n $FORCE_NAME ]]; then SAVE_NAME=$FORCE_NAME; SAVE_SSID=${SSID:-}; NAME_SOURCE=custom; else choose_name; fi
  local id=$(strftime "%Y%m%d-%H%M%S" $EPOCHSECONDS)
  { print "# WiFi Lab saved scan"; print "# Name: $SAVE_NAME"; [[ -n $SAVE_SSID ]] && print "# Wi-Fi name: $SAVE_SSID"
    print "# Name source: $NAME_SOURCE"; print "# Scanned: $SCANNED_AT"; [[ -n $SPEED_AT ]] && print "# Speed test: $SPEED_AT"; print "# Saved: $(iso_now)"; print
    local esc=${SAVE_NAME//\\/\\\\}; esc=${esc//\//\\/}; esc=${esc//&/\\&}
    sed -e "s/ this network · / $esc · /" "$1"; } > "$SAVE_DIR/$id.txt"
  printf "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n" $id "$SCANNED_AT" "$SAVE_NAME" "${SAVE_SSID:--}" "${SCORE:--}" "$(f0 $DOWN)" "$(f0 $UP)" "$(f1 ${SPING:-$IPING})" "${RSSI:--}" "${SECSCORE:--}" "${BLOCKED:-0}" "${TESTED:-0}" "${ISP:--}" >> "$HIST"
  print "  ${GR}✓ Saved “$SAVE_NAME”${R} ${GY}(scanned $SCANNED_AT) → wifilab history${R}"
}
cmd_history() {
  local rows=$(tail -n +2 "$HIST" | grep -c .)
  print; print "  ${B}${CY}💾 Saved Wi-Fi networks${R}  ${GY}$rows saved · newest first${R}"; print
  (( rows )) || { note "Nothing saved yet. Run ${B}wifilab${R}${GY} and answer yes to save, or ${B}wifilab --save \"Name\"${R}${GY}."; print; return; }
  printf "  ${GY}%-3s %-19s %-24s %5s %11s %6s %6s %5s %7s${R}\n" "#" "Scanned" "Network" "Score" "↓/↑ Mbps" "Ping" "Signal" "Sec" "Blocked"
  local n=0 nm
  tail -n +2 "$HIST" | grep . | tail -r | while IFS=$'\t' read -r id at name ssid score down up ping rssi sec blk tst isp; do
    ((n++)); [[ $ssid == - || $ssid == — ]] && ssid=""; [[ $score == - ]] && score=""; [[ $isp == - ]] && isp=""
    nm=$name; [[ -n $ssid && $ssid != $name ]] && nm="$name ($ssid)"
    printf "  ${CY}%-3s${R} %-19s ${B}%-24.24s${R} $(scol ${score:-0})%5s${R} %11s %6s %6s %5s %7s\n" $n "$at" "$nm" "${score:-—}" "$down/$up" "$ping" "${rssi:-—}" "$sec" "${blk:-0}/${tst:-0}"
  done
  print; note "wifilab show <#>   ·   wifilab rename <#> \"New name\"   ·   wifilab delete <#>"; print
}
hist_id() { tail -n +2 "$HIST" | grep . | tail -r | sed -n "${1}p" | cut -f1; }
cmd_show() { local id=$(hist_id ${1:-1}); [[ -z $id ]] && { print "  No saved scan #$1"; return 1; }; cat "$SAVE_DIR/$id.txt" | ${PAGER_CMD:-cat}; }
cmd_rename() { local id=$(hist_id $1); [[ -z $id || -z $2 ]] && { print "  Usage: wifilab rename <#> \"New name\""; return 1; }
  awk -F'\t' -v OFS='\t' -v id="$id" -v nm="$2" '$1==id{$3=nm}1' "$HIST" > "$TMP/h" && cat "$TMP/h" > "$HIST"
  local old=$(sed -n 's/^# Name: //p' "$SAVE_DIR/$id.txt" | head -1) new=${2//\\/\\\\}; new=${new//\//\\/}; new=${new//&/\\&}
  local oldre=$(print -r -- "$old" | sed 's/[]\/$*.^[]/\\&/g')
  sed -i '' -e "s/^# Name: .*/# Name: $new/" -e "s/ $oldre · / $new · /" "$SAVE_DIR/$id.txt"; print "  ${GR}✓ Renamed to “$2”${R}"; }
cmd_delete() { local id=$(hist_id $1); [[ -z $id ]] && { print "  No saved scan #$1"; return 1; }
  local nm=$(awk -F'\t' -v id="$id" '$1==id{print $3}' "$HIST"); local yn; read -r "yn?  Delete “$nm”? This can't be undone. [y/N] "
  [[ $yn == [yY]* ]] || return; awk -F'\t' -v id="$id" '$1!=id' "$HIST" > "$TMP/h" && cat "$TMP/h" > "$HIST"; rm -f "$SAVE_DIR/$id.txt"; print "  ${GR}✓ Deleted${R}"; }

# ───────────────────────────────── live signal hunter
cmd_signal() {
  read_radio; (( CONNECTED )) || { print "  Not connected to Wi-Fi."; return 1; }
  print; print "  ${B}${CY}🎯 Signal hunter${R}  ${GY}walk around · press ${B}s${R}${GY} to save a spot · ${B}q${R}${GY} to quit${R}"; print
  local -a hist spots; local best=-200 k
  while :; do
    read_radio
    hist+=($RSSI); (( ${#hist} > 40 )) && hist=(${hist[-40,-1]})
    local pct=$(( (RSSI + 90) / 60.0 * 100 )); (( pct < 0 )) && pct=0
    local sp=""; local ch=(▁ ▂ ▃ ▄ ▅ ▆ ▇ █) x; for x in $hist; do local i=$(( int((x + 90) / 60.0 * 7) + 1 )); (( i < 1 )) && i=1; (( i > 8 )) && i=8; sp+=${ch[$i]}; done
    printf "\r\e[K  ${B}%4s dBm${R} %s %s  ${GY}SNR %s · %s Mbps${R}  ${CY}%s${R}" $RSSI "$(bar $pct 20)" "$(rssi_q $RSSI)" "${SNR:-—}" "${RATE:-?}" "$sp"
    if read -t 2 -k 1 k; then
      [[ $k == q ]] && break
      if [[ $k == s ]]; then local nm; print; read -r "nm?  Name this spot: "; spots+=("$RSSI|${RATE:-?}|${nm:-Spot ${#spots}}"); print; fi
    fi
  done
  print; (( ${#spots} )) || return
  print; print "  ${B}🏆 Best spots${R}"
  for s in ${(On)spots}; do IFS='|' read -r r rt nm <<< "$s"; printf "  %-24s %s dBm  %s Mbps\n" "$nm" "$r" "$rt"; done | sort -t' ' -k2 -n
}

# ───────────────────────────────── main
usage() {
  cat <<EOF

  ${B}${CY}📡 WiFi Lab${R} ${GY}terminal edition v$VERSION${R}

  ${B}wifilab${R}                    Full scan: radio, network, speed, blocks, security, facts
  ${B}wifilab --no-speed${R}         Skip the speed test (saves data)
  ${B}wifilab --quick${R}            Radio + network + speed only (no block/port checks)
  ${B}wifilab --save "Name"${R}      Scan and save under a custom name, no questions
  ${B}wifilab speed${R}              Just the speed test
  ${B}wifilab blocks${R}             Just the "what's blocked" check
  ${B}wifilab signal${R}             Live signal hunter: walk around to find the best spot
  ${B}wifilab history${R}            List saved Wi-Fi networks
  ${B}wifilab show <#>${R}           Reopen a saved scan exactly as it was
  ${B}wifilab rename <#> "Name"${R}  Rename a saved scan
  ${B}wifilab delete <#>${R}         Delete a saved scan
  ${B}wifilab app${R}                Open the full visual dashboard (needs Python 3)

  Saved scans live in ${GY}$DATA_DIR${R}

EOF
}

cmd_scan() {
  show_header; print
  SCANNED_AT=$(iso_now)
  ( read_radio; typeset -p IFACE CH BAND WIDTH RSSI NOISE PHY SEC RATE MCS CARD PHYS COUNTRY MYMAC SSID SECDETAIL NEAR_COUNT CONNECTED SNR > "$TMP/radio.env" ) & spin $! "Listening to the airwaves"
  source "$TMP/radio.env"
  ( read_network; typeset -p IP MASK GW DHCPSRV RELAY LEASE DOMAIN DNS DNSPROV PUBIP ORG CITY REGION PHOST ISP COLO TLSV KEX IPING IJIT ILOSS GWPING GWJIT GWLOSS GWMAC GWVENDOR IPV6 CAPTIVE HOPS INTERCEPT EXTDNS_OK MACFW ARPN PRIVMAC > "$TMP/net.env" ) & spin $! "Reading the network"
  source "$TMP/net.env"
  if [[ -z $QUICK ]]; then
    ( run_blocks; typeset -p BLOCKED TESTED FREEDOM > "$TMP/blk.env" ) & spin $! "Checking what's blocked (39 sites)"
    source "$TMP/blk.env"
    run_ports & spin $! "Testing outgoing ports"
  fi
  [[ -z $NOSPEED ]] && run_speed
  compute_scores
  { show_score; show_speed_summary; show_insights; show_security; show_facts; [[ -z $QUICK ]] && show_blocks; show_radio; show_airwaves; show_nerd; [[ -z $QUICK ]] && show_ports; print; } > "$TMP/report.txt"
  cat "$TMP/report.txt"
  hr
  if [[ -n $FORCE_NAME ]]; then save_scan "$TMP/report.txt" force
  elif [[ -t 0 ]]; then local yn; read -r "yn?  💾 Save this Wi-Fi to history? [y/N] "; [[ $yn == [yY]* ]] && save_scan "$TMP/report.txt"; fi
  print
}

[[ $(uname) == Darwin ]] || { print "WiFi Lab terminal edition needs macOS."; exit 1; }
args=("$@"); args=(${args:#--no-color})
case ${args[1]:-scan} in
  scan|--no-speed|--quick|--save)
    for ((i=1;i<=${#args};i++)); do case ${args[$i]} in --no-speed) NOSPEED=1;; --quick) QUICK=1;; --save) FORCE_NAME=${args[$((i+1))]:-Unnamed Wi-Fi};; esac; done
    cmd_scan;;
  speed)   show_header; IFACE=$(wifi_iface); IFACE=${IFACE:-en0}; COLO=$(curl -s --max-time 5 https://www.cloudflare.com/cdn-cgi/trace | awk -F= '/^colo=/{print $2}'); run_speed; show_speed_summary; print;;
  blocks)  show_header; print; ( run_blocks; typeset -p BLOCKED TESTED FREEDOM > "$TMP/blk.env" ) & spin $! "Checking what's blocked (39 sites)"; source "$TMP/blk.env"; show_blocks; print;;
  signal)  cmd_signal;;
  history|list|ls) cmd_history;;
  show)    cmd_show ${args[2]:-1};;
  rename)  cmd_rename ${args[2]} "${args[3]}";;
  delete|rm) cmd_delete ${args[2]};;
  app)     for d in "$DATA_DIR/app" "${0:A:h}/../app" "${0:A:h}/.."; do [[ -f "$d/wifi_lab.py" ]] && exec python3 "$d/wifi_lab.py"; done
           print "  Full app not found. Install it with the WiFi Lab download (install.sh)."; exit 1;;
  help|-h|--help) usage;;
  version|-v|--version) print "wifilab $VERSION";;
  *) usage; exit 1;;
esac
