#!/usr/bin/env bash
# RCA: процесс жив, окна нет — логи + процессы (без Apple Events).
set -euo pipefail
GOG_DIR="$(cd "$(dirname "$0")" && pwd)"
# shellcheck source=config.sh
source "${GOG_DIR}/config.sh"

OUT="${1:-${HOME}/code/local_machine/temp/gog-window-rca-$(date +%Y%m%d-%H%M%S)}"
mkdir -p "${OUT}"

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"
LAUNCH_LOG="/tmp/gog-galaxy-client-${BOTTLE_NAME}.log"

{
  echo "=== GOG Galaxy window RCA ==="
  date
  echo "bottle: ${BOTTLE_NAME} ${BOTTLE_ID}"
  echo "GOG_USE_WINEVDESKTOP=${GOG_USE_WINEVDESKTOP:-?} GOG_VDESKTOP=${GOG_VDESKTOP:-?}"
  echo ""
  echo "--- pgrep Galaxy ---"
  pgrep -fl 'GalaxyClient|explorer.exe /desktop=GOG' 2>/dev/null || echo "(нет процессов)"
  echo ""
  echo "--- disk ---"
  df -h "$(gog_data_volume_path)" 2>/dev/null | tail -1
} >"${OUT}/summary.txt"

for f in "${GALAXY_LOG}" "${INIT_LOG}" "${CEF_LOG}" "${LAUNCH_LOG}"; do
  [[ -f "${f}" ]] || continue
  base="$(basename "${f}")"
  tail -80 "${f}" >"${OUT}/${base}.tail" 2>/dev/null || true
done

grep -E 'Second client|will continue|Showing login|foreground|Failed to locate|parent window' \
  "${GALAXY_LOG}" "${CEF_LOG}" 2>/dev/null >"${OUT}/signals.txt" || true

echo "OK: ${OUT}"
echo "  summary.txt, signals.txt, *.tail"
echo ""
echo "Если в signals.txt есть login/foreground, а окна нет:"
echo "  bash ${GOG_DIR}/reset.sh"
echo "  bash ${GOG_DIR}/launch-galaxy-ui.sh   # vdesktop + foreground"
echo "  Cmd+Tab → wine64 / GOGGalaxy / GalaxyClient"
