#!/usr/bin/env bash
set -euo pipefail

ROOT_DIR="$(cd "$(dirname "$0")" && pwd)"
DESKTOP_DIR="$ROOT_DIR/desktop"
PORT="${PORT:-1420}"
WEB_URL="http://localhost:$PORT"
LOG_DIR="$ROOT_DIR/.maestro-desktop/logs"
KEEP_OPEN="${KEEP_OPEN:-0}"

while [[ $# -gt 0 ]]; do
  case "$1" in
    --interactive|--keep-open)
      KEEP_OPEN=1
      shift
      ;;
    -h|--help)
      echo "usage: ./test-desktop.sh [--interactive|--keep-open]"
      exit 0
      ;;
    *)
      echo "unknown argument: $1" >&2
      exit 2
      ;;
  esac
done

mkdir -p "$LOG_DIR"

kill_port() {
  local port="$1"
  if command -v lsof >/dev/null 2>&1; then
    local pids
    pids="$(lsof -ti tcp:"$port" 2>/dev/null || true)"
    if [[ -n "$pids" ]]; then
      # shellcheck disable=SC2086
      kill $pids 2>/dev/null || true
    fi
  fi
}

cleanup() {
  if [[ "$KEEP_OPEN" != "1" ]]; then
    if [[ -n "${TAURI_PID:-}" ]]; then
      kill "$TAURI_PID" 2>/dev/null || true
    fi
    kill_port "$PORT"
  fi
}
trap cleanup EXIT

kill_port "$PORT"

if [[ ! -d "$DESKTOP_DIR/node_modules" ]]; then
  (cd "$DESKTOP_DIR" && npm install)
fi

export PORT
export RHO_REPO_ROOT="$ROOT_DIR"

(cd "$DESKTOP_DIR" && npm run tauri:dev >"$LOG_DIR/tauri.log" 2>&1) &
TAURI_PID=$!

for _ in $(seq 1 900); do
  if curl -fsS "$WEB_URL" >/dev/null 2>&1; then
    break
  fi
  sleep 1
done

if ! curl -fsS "$WEB_URL" >/dev/null 2>&1; then
  echo "Vite did not become ready at $WEB_URL" >&2
  tail -n 120 "$LOG_DIR/tauri.log" >&2 || true
  exit 1
fi

(cd "$DESKTOP_DIR" && npx playwright install chromium)

(cd "$DESKTOP_DIR" && node -e "const { chromium } = require('playwright'); (async () => { const b = await chromium.launch(); const p = await b.newPage(); await p.goto('$WEB_URL'); await p.waitForSelector('text=Rho'); await b.close(); })().catch((error) => { console.error(error); process.exit(1); });")

echo "desktop smoke test passed"
if [[ "$KEEP_OPEN" == "1" ]]; then
  echo "desktop left running at $WEB_URL"
  wait "$TAURI_PID"
fi
