#!/usr/bin/env bash
# Отдельный WINEPREFIX под Wine 7.7 из Game Porting Toolkit (D3D12 + D3DMetal).
# Whisky Wine 11 не грузит GPTK dxgi/d3d12 PE — JA3 падает на «Failed creating render device».
set -euo pipefail
GOG_DIR="$(cd "$(dirname "$0")" && pwd)"
GAMES_DIR="$(cd "${GOG_DIR}/.." && pwd)"
# shellcheck source=config.sh
source "${GOG_DIR}/config.sh"

GPTK_WINE="/Applications/Game Porting Toolkit.app/Contents/Resources/wine"
GPTK_WINE64="${GPTK_WINE}/bin/wine64"
JA3_SRC="${BOTTLE_DIR}/drive_c/GOG Games/Jagged Alliance 3"
GPTK_PREFIX="${JA3_GPTK_PREFIX:-${GAMES_CACHE_DIR}/ja3-gptk-prefix}"

[[ -x "${GPTK_WINE64}" ]] || {
  echo "❌ brew install --cask gcenx/wine/game-porting-toolkit"
  exit 1
}
[[ -f "${JA3_SRC}/JA3.exe" ]] || {
  echo "❌ Нет JA3 в bottle ${BOTTLE_NAME} — install-ja3-innoextract.sh"
  exit 1
}

export WINEARCH=win64
export WINEPREFIX="${GPTK_PREFIX}"
export WINED3DMETAL=1
export WINEMSYNC=1
export WINEDEBUG=-all
export DYLD_LIBRARY_PATH="${GPTK_WINE}/lib:${DYLD_LIBRARY_PATH:-}"

mkdir -p "${GPTK_PREFIX}"

if [[ ! -f "${GPTK_PREFIX}/system.reg" ]]; then
  echo "Инициализация GPTK prefix: ${GPTK_PREFIX}"
  "${GPTK_WINE64}" wineboot -i
fi

GOG_DRIVE="${GPTK_PREFIX}/drive_c/GOG Games"
JA3_LINK="${GOG_DRIVE}/Jagged Alliance 3"
mkdir -p "${GOG_DRIVE}"
if [[ -L "${JA3_LINK}" ]]; then
  :
elif [[ -d "${JA3_LINK}" ]]; then
  echo "  JA3 уже в prefix (не symlink)"
else
  ln -s "${JA3_SRC}" "${JA3_LINK}"
fi

# CommonLua + upscale cleanup (на исходной копии в GOG bottle)
bash "${GOG_DIR}/finish-ja3-layout.sh" >/dev/null 2>&1 || true

WINE64="${GPTK_WINE64}" BOTTLE_DIR="${GPTK_PREFIX}" export_wine_env_gog
export WINED3DMETAL=1
export WINEDLLOVERRIDES="libxess,xess,dxcompiler,dxil,nvngx_dlss,XeFX,XeFX_Loader=d;gdiplus=n,b"

GAME_ID='1556263729'
KEY="HKLM\\Software\\WOW6432Node\\GOG.com\\Games\\${GAME_ID}"
"${GPTK_WINE64}" reg add "${KEY}" /v gameName /t REG_SZ /d 'Jagged Alliance 3' /f >/dev/null
"${GPTK_WINE64}" reg add "${KEY}" /v exe /t REG_SZ /d 'JA3.exe' /f >/dev/null
"${GPTK_WINE64}" reg add "${KEY}" /v path /t REG_SZ /d 'C:\GOG Games\Jagged Alliance 3\' /f >/dev/null

echo "${GPTK_PREFIX}" >"${GAMES_CACHE_DIR}/.ja3_gptk_prefix"
echo "OK: GPTK prefix → ${GPTK_PREFIX}"
echo "    Запуск: bash ${GOG_DIR}/run-ja3-gptk-wine.sh"
