#!/usr/bin/env bash
# JA3 через Wine 7.7 + D3DMetal (Game Porting Toolkit). Канон для D3D12 на Apple Silicon.
set -euo pipefail
GOG_DIR="$(cd "$(dirname "$0")" && pwd)"
GAMES_DIR="$(cd "${GOG_DIR}/.." && pwd)"
# shellcheck source=config.sh
source "${GOG_DIR}/config.sh"
# shellcheck source=gog-process.sh
source "${GOG_DIR}/gog-process.sh"

GPTK_WINE="/Applications/Game Porting Toolkit.app/Contents/Resources/wine"
GPTK_WINE64="${GPTK_WINE}/bin/wine64"
JA3_WIN='C:\GOG Games\Jagged Alliance 3\JA3.exe'
MARKER="${GAMES_CACHE_DIR}/.ja3_gptk_prefix"

[[ -x "${GPTK_WINE64}" ]] || {
  echo "❌ brew install --cask gcenx/wine/game-porting-toolkit"
  exit 1
}

if [[ -f "${MARKER}" ]]; then
  GPTK_PREFIX="$(cat "${MARKER}")"
else
  GPTK_PREFIX="${JA3_GPTK_PREFIX:-${GAMES_CACHE_DIR}/ja3-gptk-prefix}"
fi

if [[ ! -f "${GPTK_PREFIX}/system.reg" ]]; then
  bash "${GOG_DIR}/setup-ja3-gptk-prefix.sh"
  GPTK_PREFIX="$(cat "${MARKER}" 2>/dev/null || echo "${GPTK_PREFIX}")"
fi

JA3_UNIX="${GPTK_PREFIX}/drive_c/GOG Games/Jagged Alliance 3"
[[ -f "${JA3_UNIX}/JA3.exe" ]] || JA3_UNIX="$(readlink "${JA3_UNIX}" 2>/dev/null || true)"
[[ -f "${JA3_UNIX}/JA3.exe" ]] || {
  echo "❌ Нет JA3 в GPTK prefix — bash ${GOG_DIR}/setup-ja3-gptk-prefix.sh"
  exit 1
}

bash "${GOG_DIR}/emergency-stop.sh" >/dev/null 2>&1 || gog_kill_all
sleep 2

if [[ "${JA3_IGNORE_SWAP:-0}" != "1" ]] && ! gog_swap_guard "${JA3_SWAP_MAX_MB:-800}"; then
  exit 1
fi

export WINEPREFIX="${GPTK_PREFIX}"
export WINEARCH=win64
export WINED3DMETAL=1
export WINEMSYNC=1
export WINEDEBUG=-all
export MVK_CONFIG_LOG_LEVEL=0
export DYLD_LIBRARY_PATH="${GPTK_WINE}/lib:${DYLD_LIBRARY_PATH:-}"
export WINEDLLOVERRIDES="libxess,xess,dxcompiler,dxil,nvngx_dlss,XeFX,XeFX_Loader=d;gdiplus=n,b"

echo "Запуск JA3 (GPTK Wine 7.7 + D3DMetal, prefix ${GPTK_PREFIX})…"
cd "${JA3_UNIX}"
exec "${GPTK_WINE64}" "${JA3_WIN}" ${JA3_EXTRA_ARGS:--unpacked}
