@echo off
setlocal enabledelayedexpansion
chcp 65001 >nul
REM == DsmTool single-exe build (NativeAOT) ==
REM NativeAOT linker fails on non-ASCII paths, so copy sources to an ASCII temp
REM dir, build there, then copy the exe back. Requires: .NET SDK + VS C++ workload.

set "PROJ=%~dp0"
set "WORK=%TEMP%\dsmbuild_ascii"

echo [1/4] copy sources to %WORK%
if exist "%WORK%" rmdir /s /q "%WORK%"
mkdir "%WORK%"
xcopy "%PROJ%*.cs"       "%WORK%\" /y >nul
xcopy "%PROJ%*.csproj"   "%WORK%\" /y >nul
xcopy "%PROJ%*.axaml"    "%WORK%\" /y >nul
xcopy "%PROJ%*.manifest" "%WORK%\" /y >nul
xcopy "%PROJ%native\*"   "%WORK%\native\" /y /i >nul

echo [2/4] locate Visual C++ (vcvars64)
set "VCV="
for %%E in (Enterprise Professional Community BuildTools) do (
  if not defined VCV if exist "C:\Program Files\Microsoft Visual Studio\2022\%%E\VC\Auxiliary\Build\vcvars64.bat" set "VCV=C:\Program Files\Microsoft Visual Studio\2022\%%E\VC\Auxiliary\Build\vcvars64.bat"
)
for %%E in (Enterprise Professional Community BuildTools) do (
  if not defined VCV if exist "C:\Program Files (x86)\Microsoft Visual Studio\2022\%%E\VC\Auxiliary\Build\vcvars64.bat" set "VCV=C:\Program Files (x86)\Microsoft Visual Studio\2022\%%E\VC\Auxiliary\Build\vcvars64.bat"
)
if not defined VCV (
  echo [ERROR] vcvars64.bat not found. Install VS 2022 "Desktop development with C++".
  exit /b 1
)
set "PATH=%PATH%;C:\Program Files (x86)\Microsoft Visual Studio\Installer"
call "%VCV%" >nul

echo [3/4] publish NativeAOT single exe
pushd "%WORK%"
dotnet publish -c Release
set "ERR=%ERRORLEVEL%"
popd
if not "%ERR%"=="0" ( echo [ERROR] publish failed %ERR% & exit /b %ERR% )

echo [4/4] copy exe back
if not exist "%PROJ%..\..\exe" mkdir "%PROJ%..\..\exe"
copy /y "%WORK%\bin\x64\Release\net9.0\win-x64\publish\DsmTool.exe" "%PROJ%..\..\exe\DsmTool.exe" >nul
echo DONE: "%PROJ%..\..\exe\DsmTool.exe"
endlocal
