#!/bin/sh
# TLS 标注包 - macOS / Linux 启动脚本。双击或在终端里运行都可以。
set -e
cd "$(dirname "$0")"

PORT="${TLS_PORT:-8731}"
while :; do
  if ! (exec 3<>/dev/tcp/127.0.0.1/$PORT) 2>/dev/null; then break; fi
  PORT=$((PORT+1))
done

PY=""
for c in python3 python; do
  if command -v "$c" >/dev/null 2>&1; then PY="$c"; break; fi
done
if [ -z "$PY" ]; then
  echo "找不到 python。"
  echo "Ubuntu: sudo apt install python3"
  echo "或者直接用浏览器打开 viewer/index.html（功能相同，但请务必用“导出全部”保存）"
  exit 1
fi

echo "启动本地服务： http://127.0.0.1:$PORT/viewer/index.html"
echo "关闭这个窗口即停止服务。"

"$PY" -m http.server "$PORT" --bind 127.0.0.1 >/dev/null 2>&1 &
SRV=$!
sleep 1

for op in xdg-open open; do
  if command -v "$op" >/dev/null 2>&1; then
    "$op" "http://127.0.0.1:$PORT/viewer/index.html" >/dev/null 2>&1 && break
  fi
done

trap 'kill $SRV 2>/dev/null' INT TERM
wait $SRV