#!/usr/bin/env bash
# Brand-agnostic Sovereign Suite Desktop Launcher (Wave 5 — 5 Flagship Studios)
# Opens Alfred Chat, Alfred Agents, Alfred Media Studio, Alfred IDE, or Control Panel inside :8080 when active,
# falling back cleanly to local loopback ports on standalone workstations.
TARGET="${1:-panel}"

resolve_panel_base() {
  if [ -s /etc/alfred/suite-public-host ]; then
    H="$(head -n1 /etc/alfred/suite-public-host | tr -d '[:space:]')"
    [ -n "$H" ] && { echo "https://${H}:8080"; return 0; }
  fi
  LIP="$(ip -4 route get 1.1.1.1 2>/dev/null | awk '{for(i=1;i<=NF;i++) if($i=="src"){print $(i+1); exit}}')"
  if [ -n "$LIP" ] && ss -ltn 2>/dev/null | grep -q ":8080 "; then
    echo "https://${LIP}:8080"
    return 0
  fi
  return 1
}

if BASE="$(resolve_panel_base)"; then
  case "$TARGET" in
    chat)   URL="${BASE}/chat/" ;;
    agents) URL="${BASE}/agents/" ;;
    studio) URL="${BASE}/studio" ;;
    ide)    URL="${BASE}/alfred-ide/" ;;
    *)      URL="${BASE}/index.php#dashboard" ;;
  esac
else
  case "$TARGET" in
    chat)   URL="http://127.0.0.1:18086" ;;
    agents) URL="http://127.0.0.1:18087/" ;;
    studio) URL="http://127.0.0.1:3095/studio" ;;
    ide)    URL="http://127.0.0.1:8443/alfred-ide/" ;;
    *)      URL="https://127.0.0.1:8080/login/" ;;
  esac
fi

if command -v xdg-open >/dev/null 2>&1; then
  nohup xdg-open "$URL" >/dev/null 2>&1 &
elif command -v chromium >/dev/null 2>&1; then
  nohup chromium "$URL" >/dev/null 2>&1 &
fi
exit 0
