@echo off
setlocal EnableDelayedExpansion

set "ROOT_DIR=%~dp0.."
if "%~1"=="" (
    set "CONFIG_FILE=%USERPROFILE%\Saleculator.properties"
) else (
    set "CONFIG_FILE=%~1"
)
set "STATUS=0"

echo Saleculator preflight
echo Root: %ROOT_DIR%
echo Config: %CONFIG_FILE%
echo.

where java >nul 2>nul
if errorlevel 1 (
    echo FAIL: java is not on PATH
    set "STATUS=1"
) else (
    for /f "delims=" %%I in ('where java') do (
        echo PASS: java found: %%I
        goto :java_found
    )
)
:java_found
java -version 2>&1
set "JAVA_VERSION=0"
for /f "tokens=3" %%V in ('java -version 2^>^&1 ^| findstr /i "version"') do set "JAVA_VERSION=%%~V"
for /f "tokens=1,2 delims=." %%A in ("%JAVA_VERSION%") do (
    if "%%A"=="1" (
        set "JAVA_MAJOR=%%B"
    ) else (
        set "JAVA_MAJOR=%%A"
    )
)
if not defined JAVA_MAJOR set "JAVA_MAJOR=0"
if %JAVA_MAJOR% LSS 8 (
    echo FAIL: Java 8 or newer is required; detected major version %JAVA_MAJOR%
    set "STATUS=1"
) else (
    echo PASS: Java major version is %JAVA_MAJOR%
)

if exist "%ROOT_DIR%\dist\Saleculator.jar" (
    echo PASS: application jar exists
) else (
    echo FAIL: missing dist\Saleculator.jar; runtime package is incomplete
    set "STATUS=1"
)

if exist "%ROOT_DIR%\lib" (echo PASS: lib directory exists) else (echo FAIL: missing lib directory & set "STATUS=1")
if exist "%ROOT_DIR%\lib\mysql-connector-java-5.1.7-bin.jar" (echo PASS: legacy MySQL driver exists) else echo WARN: legacy MySQL driver is missing
if exist "%ROOT_DIR%\lib\mysql-connector-j-8.4.0.jar" (echo PASS: current MySQL driver exists) else echo WARN: current MySQL driver is missing
if exist "%ROOT_DIR%\lib\jSerialComm-2.7.0.jar" (echo PASS: jSerialComm exists) else echo WARN: jSerialComm is missing; serial printers/scales may fail
if exist "%ROOT_DIR%\lib\Windows\hidapi-jni.dll" (echo PASS: Windows HID native library exists) else echo WARN: Windows HID native library is missing

if exist "%CONFIG_FILE%" (
    echo PASS: config file exists
    call :print_prop "db.URL"
    call :print_prop "db.driver"
    call :print_prop "db.driverlib"
    call :print_prop "machine.printer"
    call :print_prop "machine.scale"
    call :print_prop "machine.scanner"
) else (
    echo WARN: config file not found; app will use built-in defaults on first run
)

echo.
if "%STATUS%"=="0" (
    echo Preflight completed without hard failures.
) else (
    echo Preflight found hard failures.
)
exit /b %STATUS%

:print_prop
set "KEY=%~1"
set "VALUE="
for /f "usebackq tokens=1,* delims==" %%A in ("%CONFIG_FILE%") do (
    if "%%A"=="%KEY%" set "VALUE=%%B"
)
if defined VALUE (
    echo INFO: %KEY%=%VALUE%
) else (
    echo WARN: %KEY% is blank or not set
)
exit /b 0
