#!/usr/bin/env bash
# Launch NexusOS as a standalone Edge app window. Single-process mode: the
# backend on :8000 serves the built web UI itself (no separate Vite), so this
# only starts the memory service + backend. The AI (Ollama) does NOT auto-start
# — turn it on from the UI's Start AI button. Closing the app window shuts the
# services back down (matches the launcher's "closing the window shuts it down").
NEXUS_ROOT="$(cd "$(dirname "$(realpath "$0")")/.." && pwd)"
EDGE_PROFILE="$HOME/.config/nexus-edge"
APP_URL="http://localhost:8000"

# If the app is already open, just raise another window in the existing
# instance and leave the services alone — this launch doesn't own them.
if pgrep -f "user-data-dir=$EDGE_PROFILE" >/dev/null 2>&1; then
    exec microsoft-edge-stable --user-data-dir="$EDGE_PROFILE" --app="$APP_URL"
fi

# Own the services (and stop them on exit) only if WE start them. If the stack
# is already up — started elsewhere (ncp start, the control panel) — this launch
# is just a viewer and must not tear down someone else's services on close.
# Backend on :8000 is the sentinel for "stack already running".
if curl -s --max-time 1 "$APP_URL/" >/dev/null 2>&1; then
    OWN_SERVICES=0
else
    OWN_SERVICES=1
    # Single-process app: memory + backend only. Backend serves the built UI at
    # :8000; no frontend/Vite process, no AI auto-start.
    "$NEXUS_ROOT/management/nexus-cli.sh" start -m
    "$NEXUS_ROOT/management/nexus-cli.sh" start -b
fi

# Shut the services back down whenever this script ends — whether Edge exits
# normally (window closed) or the script is itself terminated (SIGTERM/SIGHUP
# from the session/WM). Only armed when we started the stack.
[ "$OWN_SERVICES" = 1 ] && trap '"$NEXUS_ROOT/management/nexus-cli.sh" stop' EXIT

# Run the app in its OWN Edge profile (--user-data-dir). Without this, the
# --class=NexusOS window becomes the Chromium "singleton owner" of the default
# profile, so every later browser window inherits WM_CLASS=NexusOS. A separate
# profile keeps only the app window NexusOS-class; regular browsing stays its own.
#
# Runs in the FOREGROUND, blocking until the app window is closed.
# --disable-background-mode is essential: without it Edge keeps a background
# process alive after the last window closes, so this call never returns and the
# services are never stopped.
microsoft-edge-stable \
    --user-data-dir="$EDGE_PROFILE" \
    --no-first-run \
    --no-default-browser-check \
    --disable-background-mode \
    --class=NexusOS \
    --app="$APP_URL"
