#!/usr/bin/env bash
# announce-control-center.sh — after install/start, surface the Control Center URL
# and best-effort open it in a browser.
#
# Generic + env-driven (no hardcoded hosts). Honest about headless servers: a
# machine with no display (a typical EC2 box) CANNOT pop a browser, so we print
# a prominent, copy-pasteable URL; a machine WITH a display auto-opens it.
#
# Env:
#   AIVIBECLAW_GATEWAY_PORT   gateway port (default 18789)
#   AIVIBECLAW_PUBLIC_IP      public IPv4 override (matches the runtime's
#                             detectPublicIp order; skips auto-detection).
#   CONTROL_SCHEME            http|https for the ip:port URL (default http; the
#                             installer passes https once gateway TLS is enabled).
#   CONTROL_DOMAIN            optional public domain fronting the gateway (e.g. a
#                             reverse proxy). When set, the announced URL is
#                             https://$CONTROL_DOMAIN (the reachable public URL).
#   CONTROL_URL               optional fully-formed URL override (wins over all).
#   AIVIBECLAW_NO_OPEN=1      never attempt to open a browser (print only).
set -euo pipefail

PORT="${AIVIBECLAW_GATEWAY_PORT:-18789}"
SCHEME="${CONTROL_SCHEME:-http}"
case "$SCHEME" in
  http|https) ;;
  *) echo "[announce] invalid CONTROL_SCHEME '$SCHEME' (use http or https)" >&2; exit 2 ;;
esac

# --- detect the machine's public IPv4 (best effort, never fatal) --------------
detect_public_ip() {
  # 0) Explicit override (same order as the runtime's detectPublicIp).
  case "${AIVIBECLAW_PUBLIC_IP:-}" in
    *.*.*.*) printf '%s' "$AIVIBECLAW_PUBLIC_IP"; return 0 ;;
  esac
  # 1) EC2 IMDSv2 (token-authenticated metadata) — the correct source on AWS.
  local tok ip
  tok="$(curl -s -m 2 -X PUT "http://169.254.169.254/latest/api/token" \
    -H "X-aws-ec2-metadata-token-ttl-seconds: 60" 2>/dev/null || true)"
  if [ -n "$tok" ]; then
    ip="$(curl -s -m 2 -H "X-aws-ec2-metadata-token: $tok" \
      "http://169.254.169.254/latest/meta-data/public-ipv4" 2>/dev/null || true)"
    [ -n "$ip" ] && { printf '%s' "$ip"; return 0; }
  fi
  # 2) Generic public-IP echo services (works off-AWS too).
  for svc in "https://api.ipify.org" "https://ifconfig.me/ip" "https://checkip.amazonaws.com"; do
    ip="$(curl -s -m 3 "$svc" 2>/dev/null | tr -d '[:space:]' || true)"
    case "$ip" in
      *.*.*.*) printf '%s' "$ip"; return 0 ;;
    esac
  done
  return 1
}

# --- resolve the URL a human should open --------------------------------------
resolve_url() {
  if [ -n "${CONTROL_URL:-}" ]; then printf '%s' "$CONTROL_URL"; return 0; fi
  if [ -n "${CONTROL_DOMAIN:-}" ]; then printf 'https://%s' "$CONTROL_DOMAIN"; return 0; fi
  local pub; pub="$(detect_public_ip || true)"
  if [ -n "$pub" ]; then printf '%s://%s:%s' "$SCHEME" "$pub" "$PORT"; return 0; fi
  printf '%s://127.0.0.1:%s' "$SCHEME" "$PORT"
}

URL="$(resolve_url)"
PUBLIC_IP="$(detect_public_ip || echo "unknown")"

# --- can we actually open a browser here? -------------------------------------
# An explicit AIVIBECLAW_OPEN_URL command (e.g. an SSH operator forwarding the
# open to their own laptop, or a WSL/Termux bridge) always counts as launchable
# — it is the operator's chosen way to surface the URL on a machine WITH a
# display, even though the server itself is headless.
has_display() {
  [ "${AIVIBECLAW_NO_OPEN:-0}" = "1" ] && return 1
  [ -n "${AIVIBECLAW_OPEN_URL:-}" ] && return 0
  case "$(uname -s)" in
    Darwin) command -v open >/dev/null 2>&1 ;;                 # macOS GUI
    # WSL exposes a Windows browser opener even without an X display.
    *) command -v wslview >/dev/null 2>&1 && return 0
       command -v termux-open-url >/dev/null 2>&1 && return 0  # Android/Termux
       # Native Linux desktop needs an X/Wayland display AND an opener.
       [ -n "${DISPLAY:-}${WAYLAND_DISPLAY:-}" ] && \
         { command -v google-chrome >/dev/null 2>&1 \
           || command -v chromium >/dev/null 2>&1 \
           || command -v xdg-open >/dev/null 2>&1; } ;;
  esac
}

# Prefer Chrome specifically; fall back through every opener we can find. Never
# fatal. A custom AIVIBECLAW_OPEN_URL command wins (its {} is replaced with the
# url, or the url is appended when it has no placeholder).
open_browser() {
  local url="$1"
  if [ -n "${AIVIBECLAW_OPEN_URL:-}" ]; then
    case "$AIVIBECLAW_OPEN_URL" in
      *'{}'*) eval "${AIVIBECLAW_OPEN_URL//\{\}/$url}" >/dev/null 2>&1 || true ;;
      *) eval "$AIVIBECLAW_OPEN_URL \"$url\"" >/dev/null 2>&1 || true ;;
    esac
    return 0
  fi
  case "$(uname -s)" in
    Darwin) open -a "Google Chrome" "$url" >/dev/null 2>&1 || open "$url" >/dev/null 2>&1 || true ;;
    *) google-chrome "$url" >/dev/null 2>&1 \
       || chromium "$url" >/dev/null 2>&1 \
       || wslview "$url" >/dev/null 2>&1 \
       || termux-open-url "$url" >/dev/null 2>&1 \
       || xdg-open "$url" >/dev/null 2>&1 || true ;;
  esac
}

cat <<BANNER

==============================================================================
  AiVibeClaw Control Center is hosted on this machine.
------------------------------------------------------------------------------
  Open it here:   $URL
  Public IP:      $PUBLIC_IP        (gateway port: $PORT)
==============================================================================
BANNER

if has_display; then
  echo "  Display detected — opening the Control Center in your browser…"
  open_browser "$URL"
else
  echo "  Headless machine (no display) — open the URL above from your laptop/phone."
  echo "  Tip: set CONTROL_DOMAIN=<your-domain> for a clean https:// URL via your proxy."
fi
