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

APP_HOME="${SOLAR_DESKTOP_HOME:-$HOME/.local/opt/solar-desktop}"
CONFIG_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/solar-desktop"
ENV_FILE="${SOLAR_DESKTOP_ENV_FILE:-$CONFIG_DIR/solar-desktop.conf}"

if [[ ! -r "$ENV_FILE" ]]; then
  echo "No se encontro la configuracion de SolaR Desktop: $ENV_FILE" >&2
  echo "Ejecuta primero ./install-desktop.sh" >&2
  exit 1
fi

set -a
# shellcheck disable=SC1090
. "$ENV_FILE"
set +a

PORT="${DEVRA_BIND_PORT:-8765}"
HOST="${DEVRA_BIND_HOST:-127.0.0.1}"
URL="http://${HOST}:${PORT}/ide"
LOG_DIR="${DEVRA_LOG_DIR:-$HOME/.local/share/solar-desktop/logs}"
PID_FILE="${XDG_RUNTIME_DIR:-/tmp}/solar-desktop-${USER}.pid"
LOCK_FILE="${XDG_RUNTIME_DIR:-/tmp}/solar-desktop-${USER}.lock"
LOG_FILE="$LOG_DIR/solar-desktop-backend.log"
mkdir -p "$LOG_DIR"

BACKEND="$APP_HOME/closed/solar-workbench-backend"
if [[ -x "$BACKEND/solar-workbench-backend" ]]; then
  BACKEND="$BACKEND/solar-workbench-backend"
fi
if [[ ! -x "$BACKEND" ]]; then
  echo "No se encontro el backend cerrado de SolaR Desktop en $APP_HOME/closed." >&2
  exit 1
fi

select_native_launcher() {
  local candidate launcher_dir="$APP_HOME/closed/solar-desktop-launcher"
  for candidate in \
    "$launcher_dir/solar-desktop-launcher-4.1" \
    "$launcher_dir/solar-desktop-launcher-4.0" \
    "$launcher_dir/solar-desktop-launcher"; do
    if [[ -x "$candidate" ]] && "$candidate" --check >/dev/null 2>&1; then
      printf '%s\n' "$candidate"
      return 0
    fi
  done
  return 1
}

LAUNCHER="$(select_native_launcher || true)"
USE_BROWSER=0
if [[ "${1:-}" == "--browser" ]]; then
  USE_BROWSER=1
  shift
fi

health_ok() {
  if command -v curl >/dev/null 2>&1; then
    curl -fsS "http://${HOST}:${PORT}/api/health" >/dev/null 2>&1
    return $?
  fi
  if command -v wget >/dev/null 2>&1; then
    wget -q -O /dev/null "http://${HOST}:${PORT}/api/health" >/dev/null 2>&1
    return $?
  fi
  return 1
}

rotate_log() {
  local max_bytes="${SOLAR_DESKTOP_LOG_MAX_BYTES:-5242880}"
  local backup_count="${SOLAR_DESKTOP_LOG_BACKUP_COUNT:-3}"
  local current_size index
  [[ -f "$LOG_FILE" ]] || return 0
  current_size="$(wc -c < "$LOG_FILE" 2>/dev/null || echo 0)"
  [[ "$current_size" =~ ^[0-9]+$ ]] || return 0
  (( current_size >= max_bytes )) || return 0

  for ((index=backup_count; index>=2; index--)); do
    if [[ -f "$LOG_FILE.$((index - 1))" ]]; then
      mv -f "$LOG_FILE.$((index - 1))" "$LOG_FILE.$index"
    fi
  done
  mv -f "$LOG_FILE" "$LOG_FILE.1"
}

open_url() {
  focus_browser() {
    if command -v wmctrl >/dev/null 2>&1; then
      wmctrl -xa firefox >/dev/null 2>&1 || wmctrl -a "SolaR Desktop" >/dev/null 2>&1 || wmctrl -a "Mozilla Firefox" >/dev/null 2>&1 || true
    elif command -v xdotool >/dev/null 2>&1; then
      local window_id
      window_id="$(xdotool search --name "SolaR Desktop\\|Mozilla Firefox\\|Firefox" 2>/dev/null | tail -n 1 || true)"
      if [[ -n "$window_id" ]]; then
        xdotool windowactivate "$window_id" >/dev/null 2>&1 || true
      fi
    fi
  }
  if command -v firefox >/dev/null 2>&1; then
    if pgrep -u "$USER" -f "(^|/)firefox( |$)" >/dev/null 2>&1; then
      firefox --new-tab "$URL" >/dev/null 2>&1 &
    else
      firefox --new-window "$URL" >/dev/null 2>&1 &
    fi
    sleep 0.8
    focus_browser
    return 0
  fi
  if command -v xdg-open >/dev/null 2>&1; then
    xdg-open "$URL" >/dev/null 2>&1 &
    sleep 0.8
    focus_browser
    return 0
  fi
  echo "Abre SolaR Desktop en: $URL"
}

exec 9>"$LOCK_FILE"
if command -v flock >/dev/null 2>&1; then
  if ! flock -w 15 9; then
    echo "Otra instancia de SolaR Desktop esta arrancando. Intentalo de nuevo en unos segundos." >&2
    exit 1
  fi
fi

if [[ -s "$PID_FILE" ]]; then
  existing_pid="$(cat "$PID_FILE" 2>/dev/null || true)"
  if [[ ! "$existing_pid" =~ ^[0-9]+$ ]] || ! kill -0 "$existing_pid" >/dev/null 2>&1; then
    rm -f "$PID_FILE"
  fi
fi

if ! health_ok; then
  rotate_log
  nohup "$BACKEND" </dev/null >> "$LOG_FILE" 2>&1 &
  backend_pid="$!"
  echo "$backend_pid" > "$PID_FILE"
  for _ in $(seq 1 40); do
    if health_ok; then
      break
    fi
    if ! kill -0 "$backend_pid" >/dev/null 2>&1; then
      break
    fi
    sleep 0.25
  done
fi

if ! health_ok; then
  rm -f "$PID_FILE"
  echo "SolaR Desktop no pudo arrancar. Revisa el log: $LOG_FILE" >&2
  exit 1
fi

if command -v flock >/dev/null 2>&1; then
  flock -u 9
fi

if (( USE_BROWSER == 0 )) && [[ -n "$LAUNCHER" && -x "$LAUNCHER" ]]; then
  if [[ -z "${WEBKIT_DISABLE_DMABUF_RENDERER:-}" ]] && ! compgen -G '/dev/dri/renderD*' >/dev/null; then
    export WEBKIT_DISABLE_DMABUF_RENDERER=1
  fi
  set +e
  "$LAUNCHER" --url "$URL"
  launcher_status="$?"
  set -e
  if [[ "$launcher_status" -eq 0 ]] || ! health_ok; then
    exit 0
  fi
  echo "La interfaz nativa no esta disponible. Se abrira SolaR Desktop en el navegador." >&2
fi
open_url
