#!/usr/bin/env bash
# GOG Galaxy в GOG-bottle (CEF). По умолчанию — виртуальный desktop Wine (окно видно на Mac).
set -euo pipefail
GOG_DIR="$(cd "$(dirname "$0")" && pwd)"
# shellcheck source=config.sh
source "${GOG_DIR}/config.sh"
# shellcheck source=gog-process.sh
source "${GOG_DIR}/gog-process.sh"

LOG="/tmp/gog-galaxy-client-${BOTTLE_NAME}.log"
GALAXY_LOG="${BOTTLE_DIR}/drive_c/ProgramData/GOG.com/Galaxy/logs/GalaxyClient.log"
INIT_LOG="${BOTTLE_DIR}/drive_c/ProgramData/GOG.com/Galaxy/logs/GalaxyInitialization.log"
CEF_LOG="${BOTTLE_DIR}/drive_c/ProgramData/GOG.com/Galaxy/logs/cef.log"

gog_launch_wine() {
  local win='C:\Program Files (x86)\GOG Galaxy\GalaxyClient.exe'
  local -a args=()
  mapfile -t args < <(gog_galaxy_cef_args_array)

  cd "${BOTTLE_DIR}/drive_c"
  if [[ "${GOG_USE_WINEVDESKTOP:-1}" == "1" ]]; then
    local w h
    IFS='x' read -r w h <<< "${GOG_VDESKTOP:-1280x800}"
    echo "Режим: explorer /desktop=GOGGalaxy,${w}x${h}"
    if [[ "${GOG_LAUNCH_FG:-0}" == "1" ]]; then
      exec "${WINE64}" explorer "/desktop=GOGGalaxy,${w}x${h}" "${win}" "${args[@]}"
    fi
    nohup "${WINE64}" explorer "/desktop=GOGGalaxy,${w}x${h}" "${win}" "${args[@]}" >>"${LOG}" 2>&1 &
  else
    echo "Режим: прямой GalaxyClient (GOG_USE_WINEVDESKTOP=0)"
    if [[ "${GOG_LAUNCH_FG:-0}" == "1" ]]; then
      exec "${WINE64}" "${win}" "${args[@]}"
    fi
    nohup "${WINE64}" "${win}" "${args[@]}" >>"${LOG}" 2>&1 &
  fi
}

main() {
  gog_wine_check
  gog_swap_guard "${GOG_SWAP_MAX_MB:-400}" || exit 1
  gog_disk_guard 8 || exit 1
  if [[ ! -f "${BOTTLE_DIR}/.gog_galaxy_extract_installed" ]]; then
    echo "Сначала: bash ${GOG_DIR}/install-galaxy-extract.sh"
    exit 1
  fi
  if ! find "${BOTTLE_DIR}/drive_c/Program Files"* -name 'GalaxyClient.exe' -print -quit 2>/dev/null | grep -q .; then
    bash "${GOG_DIR}/install-galaxy-extract.sh"
  fi

  echo "Останавливаем старые процессы GOG Galaxy…"
  gog_kill_all
  pkill -f 'explorer.exe /desktop=GOGGalaxy' 2>/dev/null || true

  if gog_galaxy_running; then
    echo "❌ Galaxy всё ещё в процессах — повторите: bash ${GOG_DIR}/reset.sh"
    pgrep -fl 'Galaxy' 2>/dev/null || true
    exit 1
  fi

  export_wine_env_gog
  echo "Bottle: ${BOTTLE_NAME}"
  echo "Лог: ${LOG}"
  : >"${LOG}"

  if [[ "${GOG_LAUNCH_FG:-0}" == "1" ]]; then
    echo ""
    echo "Foreground: окно Wine привязано к этому терминалу. Закройте Galaxy — Ctrl+C."
    echo "Ищите окно «GOGGalaxy» или полосу заголовка Wine desktop."
    echo ""
    gog_launch_wine
    exit 0
  fi

  gog_launch_wine
  echo "Запуск wine64…"

  local ok=0 i
  for i in $(seq 1 30); do
    sleep 1
    if grep -q 'Second client instance detected' "${INIT_LOG}" 2>/dev/null; then
      if tail -5 "${INIT_LOG}" 2>/dev/null | grep -q 'The client will exit'; then
        echo "❌ Второй экземпляр: bash ${GOG_DIR}/reset.sh && bash $0"
        tail -8 "${INIT_LOG}"
        exit 1
      fi
    fi
    if [[ -f "${GALAXY_LOG}" ]] && grep -qE 'Showing login form|No refresh token found|will continue' "${GALAXY_LOG}" 2>/dev/null; then
      ok=1
      break
    fi
    if [[ -f "${INIT_LOG}" ]] && grep -q 'will continue' "${INIT_LOG}" 2>/dev/null; then
      ok=1
      break
    fi
    if ! gog_galaxy_running; then
      sleep 2
      if ! gog_galaxy_running; then
        break
      fi
    fi
  done

  if ! gog_galaxy_running; then
    echo "❌ GalaxyClient не остался в процессах:"
    tail -25 "${LOG}"
    [[ -f "${INIT_LOG}" ]] && tail -15 "${INIT_LOG}"
    exit 1
  fi

  sleep 2
  gog_mac_activate_wine || true

  echo ""
  echo "OK: GOG Galaxy запущен (процесс + login в логе — окно на Mac не гарантировано)."
  echo "  • Окно: bash ${GOG_DIR}/launch-galaxy-whisky.sh → Whisky → pin gog-galaxy → Run"
  echo "  • RCA/логи 7ч: docs/games/GOG_GALAXY_7H_RCA.md | collect-gog-logs-7h.sh"
  if [[ "${GOG_USE_WINEVDESKTOP:-1}" == "1" ]]; then
    echo "  • Cmd+Tab → «wine64» / «GOGGalaxy» — отдельное окно виртуального стола Wine"
  else
    echo "  • Cmd+Tab → «GalaxyClient» или «wine64»"
  fi
  echo "  • Не видно окна? bash ${GOG_DIR}/launch-galaxy-ui.sh  (vdesktop + foreground)"
  echo "  • Whisky → «${BOTTLE_NAME}» → pin gog-galaxy → Run"
  echo "  • Лог: ${GALAXY_LOG}"
  if [[ "${ok}" -eq 1 ]]; then
    echo "  • В логе login UI — войдите → Jagged Alliance 3 → Install"
    if [[ -f "${CEF_LOG}" ]] && grep -q 'parent window' "${CEF_LOG}" 2>/dev/null; then
      echo "  • cef.log: «parent window» — типично для Wine; vdesktop/Whisky Run часто лечит"
    fi
  fi
}

main "$@"
