#!/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)
#   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}"

# --- detect the machine's public IPv4 (best effort, never fatal) --------------
detect_public_ip() {
  # 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 'http://%s:%s' "$pub" "$PORT"; return 0; fi
  printf 'http://127.0.0.1:%s' "$PORT"
}

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

# --- can we actually open a browser here? -------------------------------------
has_display() {
  [ "${AIVIBECLAW_NO_OPEN:-0}" = "1" ] && return 1
  case "$(uname -s)" in
    Darwin) command -v open >/dev/null 2>&1 ;;                 # macOS GUI
    # Linux needs an X/Wayland display AND either Chrome or xdg-open to launch.
    *) [ -n "${DISPLAY:-}" ] && \
       { command -v google-chrome >/dev/null 2>&1 || command -v xdg-open >/dev/null 2>&1; } ;;
  esac
}

# Prefer Chrome specifically; fall back to the OS default. Never fatal.
open_browser() {
  case "$(uname -s)" in
    Darwin) open -a "Google Chrome" "$1" >/dev/null 2>&1 || open "$1" >/dev/null 2>&1 || true ;;
    *) google-chrome "$1" >/dev/null 2>&1 || xdg-open "$1" >/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
