#!/bin/sh
# Valantir 데스크톱 런처 (macOS · Linux)
#   이 폴더의 updater.py 로 업데이트를 확인한 뒤 앱을 실행합니다.
set -eu
DIR=$(cd "$(dirname "$0")" && pwd)
PORT=${CONDERI_AI_PORT:-8791}

# 조직/관리자 발급 키(있으면 업데이트에 사용)
[ -f "$DIR/.update/auth.env" ] && . "$DIR/.update/auth.env"

PY=""
for c in python3 python; do
  if command -v "$c" >/dev/null 2>&1; then
    if "$c" -c 'import sys; raise SystemExit(0 if sys.version_info >= (3,10) else 1)' 2>/dev/null; then
      PY=$(command -v "$c"); break
    fi
  fi
done
[ -n "$PY" ] || { echo "Python 3.10 이상이 필요합니다."; exit 1; }

healthy() {
  "$PY" - "$PORT" <<'EOF' 2>/dev/null
import sys, urllib.request
try:
    with urllib.request.urlopen("http://127.0.0.1:%s/healthz" % sys.argv[1], timeout=2) as r:
        raise SystemExit(0 if r.status == 200 else 1)
except Exception:
    raise SystemExit(1)
EOF
}

if ! healthy; then
  [ -f "$DIR/updater.py" ] && "$PY" "$DIR/updater.py" --dir "$DIR" --apply --quiet --restart none || true
fi

ENTRY="$DIR/launch_desktop.py"
[ -f "$ENTRY" ] || ENTRY="$DIR/launch_desktop.pyc"
exec "$PY" "$ENTRY" "$@"
