#!/usr/bin/env bash
# Launch `wails dev -browser=false` in background so Playwright can drive the
# real Wails frontend via its dev HTTP server.
#
# Wails dev exposes:
#   - http://localhost:34115/  -> frontend with bindings injected (Wails proxy)
#   - http://localhost:5173/   -> raw Vite dev server (no bindings)
# Playwright tests should target :34115 so bindings work.
#
# This launcher is fire-and-forget. Use scripts/check_wails_dev.sh to verify.
set -euo pipefail

APP_DIR="$(cd "$(dirname "$0")"/.. && pwd)"
LOG_FILE="${APP_DIR}/.wails_dev.log"
PID_FILE="${APP_DIR}/.wails_dev.pid"

# Kill any previous wails dev.
if [ -f "$PID_FILE" ]; then
  OLD=$(cat "$PID_FILE")
  if kill -0 "$OLD" 2>/dev/null; then
    echo "[wails-dev] killing old PID $OLD"
    kill "$OLD" 2>/dev/null || true
    sleep 1
  fi
  rm -f "$PID_FILE"
fi
pkill -f 'wails dev' 2>/dev/null || true
# Also kill any matrix_client_pc.exe left over (wails dev launches one).
taskkill.exe /IM matrix_client_pc.exe /F 2>/dev/null || true

cd "$APP_DIR"

echo "[wails-dev] starting wails dev (logs: $LOG_FILE)"
nohup wails dev -browser=false -frontenddevserverurl=http://localhost:5173 > "$LOG_FILE" 2>&1 &
echo $! > "$PID_FILE"
echo "[wails-dev] PID $(cat "$PID_FILE")"
echo "[wails-dev] fire-and-forget. Frontend will be at http://localhost:34115"
