#!/bin/bash
# MyAI launcher - starts the local backend and (optionally) opens the browser.
#
# Default mode (no args): start backend in background, print URL, exit.
# Called from XDG autostart at session start.
#
# `myai --open`: also open the browser tab via xdg-open.
# `myai --stop`: kill any running backend.

set -e -o pipefail
export LANG=C.UTF-8
export LC_ALL=C.UTF-8

SERVER=/usr/lib/myai/server.py
PORT=7070
URL="http://localhost:${PORT}"
PIDFILE="${XDG_RUNTIME_DIR:-/tmp}/myai.pid"

stop_existing() {
    if [ -f "$PIDFILE" ]; then
        pid=$(cat "$PIDFILE" 2>/dev/null || true)
        if [ -n "$pid" ] && kill -0 "$pid" 2>/dev/null; then
            kill "$pid" 2>/dev/null || true
        fi
        rm -f "$PIDFILE"
    fi
    pkill -f "$SERVER" 2>/dev/null || true
}

case "${1:-}" in
    --stop)
        stop_existing
        echo "MyAI backend stopped."
        exit 0
        ;;
    --open|"")
        ;;
    *)
        echo "Usage: $0 [--open|--stop]" >&2
        exit 1
        ;;
esac

# If already running, just open the browser (when --open) and exit.
if curl -fsS -o /dev/null "${URL}/api/status" 2>/dev/null; then
    [ "${1:-}" = "--open" ] && xdg-open "$URL" >/dev/null 2>&1 || true
    exit 0
fi

stop_existing

nohup python3 "$SERVER" >/tmp/myai.log 2>&1 &
echo $! > "$PIDFILE"

# Wait up to 10s for the backend to answer.
for _ in $(seq 1 20); do
    if curl -fsS -o /dev/null "${URL}/api/status" 2>/dev/null; then
        break
    fi
    sleep 0.5
done

if [ "${1:-}" = "--open" ]; then
    xdg-open "$URL" >/dev/null 2>&1 || true
fi

echo "MyAI is running at $URL"
