#!/usr/bin/env bash
# Почему нет окна Wine-Steam после start.sh steam-ui.
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
# shellcheck source=config.sh
source "${SCRIPT_DIR}/config.sh"

CEF_LOG="${STEAM_DIR}/logs/cef_log.txt"
CONSOLE_LOG="${STEAM_DIR}/logs/console_log.txt"

echo "=== Wine-Steam UI — диагностика ==="
echo "Bottle: ${BOTTLE_NAME} (${BOTTLE_ID})"
echo ""

echo "1) Mac Steam (мешает login / CEF):"
if homm_mac_steam_running; then
  echo "   ❌ Запущен steam_osx — killall steam_osx ipcserver"
else
  echo "   ✅ Mac Steam не мешает"
fi
echo ""

echo "2) Процессы bottle:"
if pgrep -f "${BOTTLE_ID}.*Steam\\.exe" >/dev/null 2>&1; then
  echo "   ✅ Steam.exe"
  pgrep -lf "${BOTTLE_ID}.*Steam\\.exe" 2>/dev/null | head -2 | sed 's/^/      /'
else
  echo "   ❌ Steam.exe не запущен — bash ${SCRIPT_DIR}/start.sh steam-ui"
fi
if pgrep -f "${BOTTLE_ID}.*steamwebhelper" >/dev/null 2>&1 || pgrep -f "Whisky/Bottles/${BOTTLE_ID}.*steamwebhelper" >/dev/null 2>&1; then
  echo "   ✅ steamwebhelper (CEF UI)"
  pgrep -lf 'steamwebhelper' 2>/dev/null | grep -E "${BOTTLE_ID}|Program Files \(x86\)\\\\Steam" | head -2 | sed 's/^/      /' || pgrep -lf steamwebhelper | head -1 | sed 's/^/      /'
else
  echo "   ❌ steamwebhelper нет — окно Steam (login) не появится"
  echo "      Типично: cef_log → message_window.cc Class does not exist"
fi
echo ""

echo "3) CEF-лог (последние ошибки):"
if [[ -f "${CEF_LOG}" ]]; then
  if tail -40 "${CEF_LOG}" | grep -q 'message_window.cc'; then
    echo "   ❌ message_window.cc — steamwebhelper падает / перезапускается"
    tail -40 "${CEF_LOG}" | grep 'message_window\|chrome_elf\|LdrInitialize' | tail -3 | sed 's/^/      /'
    echo "      Фикс: bash ${SCRIPT_DIR}/start.sh reset && bash ${SCRIPT_DIR}/start.sh steam-ui"
    echo "      (в start.sh уже: ${HOMM_STEAM_CEF_ARGS})"
  else
    echo "   ✅ Нет свежих message_window в хвосте cef_log"
  fi
else
  echo "   (cef_log.txt ещё нет — Steam не стартовал)"
fi
echo ""

echo "4) VGUI / шрифты (console_log):"
if [[ -f "${CONSOLE_LOG}" ]] && tail -30 "${CONSOLE_LOG}" | grep -q winFont; then
  echo "   ⚠️  winFont — пустой текст на кнопках VGUI"
  echo "      bash ${SCRIPT_DIR}/start.sh fix-steam-ui && bash ${SCRIPT_DIR}/start.sh reset && bash ${SCRIPT_DIR}/start.sh steam-ui"
else
  echo "   ✅ winFont в хвосте нет (или лог пуст)"
fi
echo ""

echo "5) Login:"
if homm_steam_logged_on; then
  echo "   ✅ Logged On"
else
  echo "   ❌ Logged Off — Retry / Enter Offline Mode в окне Steam"
fi
echo ""

echo "Где искать окно:"
echo "  • Whisky.app → bottle HoMM-OldenEra (после migrate-bottle-to-franke-whisky.sh)"
echo "  • Cmd+Tab (wine64), Mission Control"
echo "  • Не HOMM_STEAM_VDESKTOP=1 — explorer: Failed to set primary display settings"
