@echo off
setlocal

:: Arguments passed from CMake:
:: %1 = Path to magick.exe
:: %2 = Source Image
:: %3 = Destination Icon

set "MAGICK_EXE=%~1"
set "SOURCE_IMG=%~2"
set "DEST_ICO=%~3"

:: -- FOR MISSING DELEGATES / REGISTRY ERRORS ---
for %%I in ("%MAGICK_EXE%") do set "MAGICK_DIR=%%~dpI"
if "%MAGICK_DIR:~-1%"=="\" set "MAGICK_DIR=%MAGICK_DIR:~0,-1%"
set "MAGICK_HOME=%MAGICK_DIR%"
set "MAGICK_CONFIGURE_PATH=%MAGICK_DIR%"
set "MAGICK_CODER_MODULE_PATH=%MAGICK_DIR%\modules\coders"
:: ---------------------------------------------------

:: 1. Validate Source
if not exist "%SOURCE_IMG%" (
    echo [ERROR] Icon source not found at: %SOURCE_IMG%
    exit /b 1
)

:: 2. Ensure Destination Directory Exists
if not exist "%~dp3" mkdir "%~dp3"

:: 3. Generate the .ico (Nearest Neighbor / Pixel Art Mode)
echo [ICONS] Generating Pixel-Perfect Windows Icon: %DEST_ICO%

:: We use -sample (Nearest Neighbor) explicitly for each standard icon size.
:: We clone the original (index 0) for every resize to ensure maximum accuracy from the source.
"%MAGICK_EXE%" "%SOURCE_IMG%" ^
    -background none -alpha on ^
    ( -clone 0 -sample 256x256 ) ^
    ( -clone 0 -sample 128x128 ) ^
    ( -clone 0 -sample 64x64 ) ^
    ( -clone 0 -sample 48x48 ) ^
    ( -clone 0 -sample 32x32 ) ^
    ( -clone 0 -sample 16x16 ) ^
    -delete 0 ^
    "%DEST_ICO%"

if %errorlevel% neq 0 (
    echo [ERROR] ImageMagick failed to generate icon.
    exit /b %errorlevel%
)

echo [SUCCESS] Icon generated.
exit /b 0