@echo off
setlocal enabledelayedexpansion

REM Publish XYZ Print Service for Windows x64
echo ========================================
echo Publishing XYZ Print Service...
echo ========================================
echo.

REM Get the script directory and navigate to PrintService root
set "SCRIPT_DIR=%~dp0"
set "PROJECT_ROOT=%SCRIPT_DIR%.."
cd /d "%PROJECT_ROOT%"

echo Current directory: %CD%
echo.

REM Check if .csproj exists
if not exist "XYZ.PrintService.csproj" (
    echo ERROR: XYZ.PrintService.csproj not found!
    echo Expected location: %CD%\XYZ.PrintService.csproj
    echo.
    echo Please run this script from the PrintService\scripts\ directory
    pause
    exit /b 1
)

REM Check if dotnet is available
where dotnet >nul 2>&1
if %ERRORLEVEL% neq 0 (
    echo ERROR: .NET SDK not found!
    echo Please install .NET 8.0 SDK from https://dotnet.microsoft.com/download
    pause
    exit /b 1
)

echo Building and publishing...
echo.

REM Create publish directory if it doesn't exist
if not exist "publish" mkdir publish

REM Publish
dotnet publish -c Release -r win-x64 --self-contained true -p:PublishSingleFile=true -p:IncludeNativeLibrariesForSelfExtract=true -o publish

if %ERRORLEVEL% neq 0 (
    echo.
    echo ========================================
    echo ERROR: Publish failed!
    echo ========================================
    echo.
    echo Common issues:
    echo - .NET 8.0 SDK not installed
    echo - Missing dependencies
    echo - Project file corrupted
    echo.
    pause
    exit /b 1
)

REM Verify EXE was created
set "EXE_PATH=%CD%\publish\XYZ.PrintService.exe"
if not exist "%EXE_PATH%" (
    echo.
    echo ========================================
    echo ERROR: EXE file not found after publish!
    echo ========================================
    echo Expected: %EXE_PATH%
    echo.
    pause
    exit /b 1
)

echo.
echo ========================================
echo Publish successful!
echo ========================================
echo.
echo Output: %EXE_PATH%
echo File size: 
for %%A in ("%EXE_PATH%") do echo   %%~zA bytes
echo.
echo Next steps:
echo 1. Run 'scripts\install-service.bat' as Administrator
echo    OR
echo 2. Run 'scripts\build-and-install.bat' as Administrator
echo.
pause
endlocal
