#!/bin/bash
export LC_ALL=C
echo "===== TRIGGERING FRESH HARVEST (ECH enabled) ====="
systemctl start --no-block proxylab-cycle.service
sleep 5
for i in $(seq 1 64); do
  st=$(systemctl show proxylab-cycle.service -p ActiveState --value)
  case "$st" in
    activating|active|reloading) sleep 15 ;;
    *) break ;;
  esac
done
echo "final state: $(systemctl show proxylab-cycle.service -p ActiveState --value)"

echo
echo "===== CYCLE LOG ====="
tail -n 14 /var/log/proxylab-cycle.log 2>/dev/null

echo
echo "===== HEALTHY POOL ====="
python3 - <<'PY'
import json
d=json.load(open('/opt/proxy-lab/data/healthy.json'))
print('  healthy:', len(d))
for e in d[:12]:
    print('   - %-8s %-30s %-6s %6sms exit=%s' % (e.get('type'),str(e.get('server'))[:30],e.get('port'),e.get('latency_ms'),e.get('exit_ip')))
PY

echo
echo "===== SERVED OUTBOUNDS ====="
python3 - <<'PY'
import json
c=json.load(open('/opt/proxy-lab/data/serve.json'))
n=0
for o in c['outbounds'][:-1]:
    n+=1
    ech = 'ech' if (o.get('tls') or {}).get('ech') else '-'
    print('  %-4s %-8s %-30s %-6s %s' % (o.get('tag'),o.get('type'),str(o.get('server'))[:30],o.get('server_port'),ech))
print('  total outbounds:', n)
print('  group auto ->', c['outbounds'][-1]['outbounds'])
PY

echo
echo "===== LIVE PROBE ====="
for a in 127.0.0.1 172.19.0.1; do
  printf '  %-12s -> ' "$a"
  curl -s -o /dev/null -w '%{http_code} %{time_total}s\n' --max-time 15 -x "http://$a:20808" https://www.gstatic.com/generate_204 2>/dev/null
done
printf '  exit ip: '; curl -s --max-time 20 -x http://127.0.0.1:20808 https://api.ipify.org 2>/dev/null; echo
printf '  openai : '; curl -s -o /dev/null -w '%{http_code} %{time_total}s\n' --max-time 25 -x http://127.0.0.1:20808 https://api.openai.com/v1/models 2>/dev/null
