#!/usr/bin/env bash
# Aliz - Claude Code telemetry check (macOS / Linux launcher)
#
#   curl -fsSL https://aliz-check.kowlon.my.id/check.sh | bash
#
# Downloads check.py to a temporary file and runs it. Running from a real file
# rather than piping into the interpreter is what keeps the repair prompt usable.

set -euo pipefail

BASE_URL="${ALIZ_CHECK_BASE:-https://aliz-check.kowlon.my.id}"

find_python() {
  for candidate in python3 python; do
    if command -v "$candidate" >/dev/null 2>&1 &&
       "$candidate" -c 'import sys; sys.exit(0 if sys.version_info >= (3, 8) else 1)' 2>/dev/null; then
      printf '%s' "$candidate"
      return 0
    fi
  done
  return 1
}

if ! PYTHON="$(find_python)"; then
  echo "error: Python 3.8+ is required but was not found on PATH." >&2
  echo "  macOS:         xcode-select --install" >&2
  echo "  Debian/Ubuntu: sudo apt install -y python3" >&2
  exit 2
fi

TMP="$(mktemp "${TMPDIR:-/tmp}/aliz-claude-check.XXXXXX")"
trap 'rm -f "$TMP"' EXIT INT TERM

if ! curl -fsSL "$BASE_URL/check.py" -o "$TMP"; then
  echo "error: could not download $BASE_URL/check.py" >&2
  exit 2
fi

# When this launcher is itself piped from curl, stdin is the pipe rather than the
# terminal, so reconnect it to /dev/tty to keep the prompt interactive.
#
# Probe by actually opening it: in containers and CI runners /dev/tty often exists
# and passes -r, yet opening it fails with ENXIO and would kill the script.
STATUS=0
if (exec </dev/tty) 2>/dev/null; then
  "$PYTHON" "$TMP" "$@" </dev/tty || STATUS=$?
else
  "$PYTHON" "$TMP" "$@" || STATUS=$?
fi

exit "$STATUS"
