#!/usr/bin/env bash
# start-game.sh — Start the redesign server and open the workstation display.

set -euo pipefail

PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
SERVER_DIR="$PROJECT_ROOT/server"
FRONTEND_DIR="$PROJECT_ROOT/frontend"
DOMAIN="${SC_WORKSTATION_DOMAIN:-sc-workstation}"
PORT="${PORT:-3000}"
LIBVIRT_URI="${LIBVIRT_DEFAULT_URI:-qemu:///system}"

export PORT
export LIBVIRT_DEFAULT_URI="$LIBVIRT_URI"

source "$PROJECT_ROOT/tools/lib/internal-https.sh"
sc_ensure_internal_certs "$PROJECT_ROOT"
sc_export_internal_https_env

if ! command -v virsh >/dev/null 2>&1; then
    echo "ERROR: virsh is required." >&2
    exit 1
fi

if ! command -v node >/dev/null 2>&1; then
    echo "ERROR: node is required. Install Node.js 18+." >&2
    exit 1
fi

# Ensure server dependencies are installed
if [ ! -d "$SERVER_DIR/node_modules" ]; then
    echo "Installing server dependencies..."
    (cd "$SERVER_DIR" && npm install --silent)
fi

# Ensure frontend is built
if [ ! -f "$FRONTEND_DIR/dist/index.html" ]; then
    echo "Building frontend..."
    if [ ! -d "$FRONTEND_DIR/node_modules" ]; then
        (cd "$FRONTEND_DIR" && npm install --silent)
    fi
    (cd "$FRONTEND_DIR" && npm run build --silent)
fi

if ! virsh --connect "$LIBVIRT_URI" dominfo "$DOMAIN" >/dev/null 2>&1; then
    echo "ERROR: missing workstation domain: $DOMAIN" >&2
    echo "Run: bash tools/vm/build-workstation.sh --force" >&2
    exit 1
fi

_ensure_server_port() {
    local pids=""
    pids="$(sc_listen_pids "$PORT" || true)"
    if [ -z "$pids" ]; then
        return 0
    fi

    local pid
    for pid in $pids; do
        if ! sc_pid_is_repo_server "$pid" "$PROJECT_ROOT"; then
            echo "ERROR: port $PORT is already in use by an unrelated process (pid $pid)." >&2
            echo "Stop that process or set PORT to a free port before launching." >&2
            exit 1
        fi
        if sc_pid_has_internal_tls "$pid"; then
            return 1
        fi
    done

    echo "Restarting existing Sysadmin Chronicles server on port $PORT with HTTPS enabled..."
    for pid in $pids; do
        sc_stop_pid "$pid"
    done
    return 0
}

if _ensure_server_port; then
    (
        cd "$SERVER_DIR"
        node src/index.js
    ) &
    SERVER_PID=$!
    trap 'kill "$SERVER_PID" >/dev/null 2>&1 || true' EXIT
    sleep 1
fi

state="$(virsh --connect "$LIBVIRT_URI" domstate "$DOMAIN" 2>/dev/null || true)"
if [ "$state" != "running" ]; then
    virsh --connect "$LIBVIRT_URI" start "$DOMAIN" >/dev/null
fi

if command -v remote-viewer >/dev/null 2>&1; then
    spice_uri="$(virsh --connect "$LIBVIRT_URI" domdisplay "$DOMAIN" 2>/dev/null | grep spice | head -n1 || true)"
    if [ -n "$spice_uri" ]; then
        exec remote-viewer "$spice_uri"
    fi
fi

exec bash "$PROJECT_ROOT/runtime/viewer/launch-spice-viewer.sh" "$DOMAIN"
