#!/bin/bash
export LC_ALL=C
rm -rf /tmp/sbtest /tmp/sbtest2 /tmp/sbech /tmp/sbech2 /tmp/sbech3 /tmp/proxylab-deploy /tmp/dsh_*.sh /tmp/sb_schema.json 2>/dev/null
echo "temp files cleaned"

echo
echo "===== FINAL STATE ====="
printf 'proxylab-serve : %s\n' "$(systemctl is-active proxylab-serve.service)"
printf 'cycle timer    : %s (next: %s)\n' "$(systemctl is-active proxylab-cycle.timer)" "$(systemctl show proxylab-cycle.timer -p NextElapseUSecRealtime --value)"
printf 'watchdog timer : %s\n' "$(systemctl is-active proxylab-watchdog.timer)"
printf 'xray/privoxy   : %s / %s (both bound to 127.0.0.1)\n' "$(systemctl is-active xray)" "$(systemctl is-active privoxy)"
printf 'apache/mysql   : %s / %s\n' "$(systemctl is-active apache2)" "$(systemctl is-active mysql)"

echo
python3 - <<'PY'
import json
h=json.load(open('/opt/proxy-lab/data/healthy.json'))
c=json.load(open('/opt/proxy-lab/data/serve.json'))
lat=[e.get('latency_ms') or 0 for e in h]
print(f"healthy pool   : {len(h)} configs, best={min(lat)}ms median={sorted(lat)[len(lat)//2]}ms")
print(f"served         : {len(c['outbounds'])-1} outbounds in urltest group")
ech=sum(1 for o in c['outbounds'][:-1] if (o.get('tls') or {}).get('ech'))
print(f"with ECH       : {ech}/{len(c['outbounds'])-1}")
PY

echo
echo "===== REAL-WORLD LATENCY (through proxy) ====="
for u in https://www.gstatic.com/generate_204 https://api.openai.com/v1/models https://generativelanguage.googleapis.com/ https://api.anthropic.com/v1/messages; do
  printf '  %-52s ' "$u"
  curl -s -o /dev/null -w '%{http_code} %{time_total}s\n' --max-time 20 -x http://172.19.0.1:20808 "$u" 2>/dev/null
done

echo
echo "===== 9ROUTER VIEW ====="
python3 - <<'PY'
import sqlite3, json
c=sqlite3.connect('/root/.9router/db/data.sqlite')
for r in c.execute("select data from proxyPools where isActive=1"):
    d=json.loads(r[0])
    print(f"  active pool: {d.get('name')} -> {d.get('proxyUrl')} (strict={d.get('strictProxy')}, lastTested={d.get('lastTestedAt')})")
PY
