@echo Off
setlocal enabledelayedexpansion

REM Configuration flag: Set to 1 for immediate exit, 0 for goto end (debug mode)
REM IMMEDIATE_EXIT=1: Script exits immediately with error codes (production mode)
REM IMMEDIATE_EXIT=0: Script continues to :end after errors (debug mode)
set "IMMEDIATE_EXIT=1"

REM Check if this is a minimized window instance
if not DEFINED IS_AGENT_MINIMIZED set IS_AGENT_MINIMIZED=1 && start "DQV/KTAC: Agent" /min "%~dpnx0" %* && exit

echo ========================================
echo ========================================
echo =====                              =====
echo ===== Please minimize this window. =====
echo =====                              =====
echo ========================================
echo ========================================

REM Set up environment variables
set AGENT_FOLDER=%~dp0
echo Agent is running at: %AGENT_FOLDER%
%~d0
cd "%AGENT_FOLDER%"
md logs\agent 2> nul

REM Clear Java options
set JAVA_TOOL_OPTIONS=
set IBM_JAVA_OPTIONS=
set _JAVA_OPTIONS=
set JAVA_OPTIONS=
set IS_AGENT_MINIMIZED=

REM Check for local Java installation first
set "JAVA_CMD="
if exist "java\bin\java.exe" (
    set "JAVA_CMD=java\bin\java.exe"
    call :log_message "Found local Java installation: %JAVA_CMD%" "INFO"
) else (
    REM Fall back to system PATH
    java -version >nul 2>&1
    if %errorlevel% equ 0 (
        set "JAVA_CMD=java"
        call :log_message "Using system Java from PATH" "INFO"
    )
)

REM Check if Java exists (either local or system)
if "%JAVA_CMD%"=="" (
    call :log_message "ERROR: Java is not installed or not found in PATH" "ERROR"
    call :log_message "Please install Java 1.8 or higher and ensure it is in your system PATH" "ERROR"
    call :log_message "Alternatively, place a Java installation in the 'java' folder" "ERROR"
    
    call :show_error_alert "Java is not installed or not found in PATH. Please install Java 1.8 or higher."
    goto exit_1
)

REM Get Java version and check if it's 1.8 or higher
REM Use absolute path for Java version check
if "%JAVA_CMD%"=="java\bin\java.exe" (
    set "FULL_JAVA_PATH=%AGENT_FOLDER%java\bin\java.exe"
) else (
    set "FULL_JAVA_PATH=%JAVA_CMD%"
)

REM Test if Java executable works
"%FULL_JAVA_PATH%" -version >nul 2>&1
if %errorlevel% neq 0 (
    call :log_message "ERROR: Java executable failed to run: %FULL_JAVA_PATH%" "ERROR"
    goto exit_3
)

REM Use a simple approach to get Java version
"%FULL_JAVA_PATH%" -version 2>&1 | findstr /i "version" > temp_java_version.txt
if exist temp_java_version.txt (
    for /f "tokens=*" %%i in (temp_java_version.txt) do (
        set "line=%%i"
        for /f "tokens=3 delims= " %%j in ("!line!") do (
            set "java_version=%%j"
            set "java_version=!java_version:"=!"
        )
    )
    del temp_java_version.txt
) else (
    set "java_version="
)

echo [DEBUG] Raw java_version: "%java_version%"
call :log_message "Detected Java version: %java_version%" "INFO"

REM Extract major version number (e.g., "1.8.0_291" -> "1.8")

REM Check if java_version is empty
if "%java_version%"=="" (
    echo [DEBUG] java_version is empty, cannot parse version
    call :log_message "ERROR: Could not determine Java version" "ERROR"
    goto exit_3
)

for /f "tokens=1-2 delims=." %%a in ("%java_version%") do (
    set "major_version=%%a"
    set "minor_version=%%b"
)
echo [DEBUG] Parsed major_version: "%major_version%"
echo [DEBUG] Parsed minor_version: "%minor_version%"

REM Check if parsing was successful
if "%major_version%"=="" (
    echo [DEBUG] Failed to parse major version
    call :log_message "ERROR: Failed to parse Java version: %java_version%" "ERROR"
    goto exit_3
)

REM Check if version is 1.8 or higher

REM Additional safety check for empty variables
if "%major_version%"=="" (
    echo [DEBUG] major_version is empty, cannot proceed with version check
    call :log_message "ERROR: Major version is empty, cannot determine Java compatibility" "ERROR"
    goto exit_3
)

if "%major_version%"=="1" (
    if "%minor_version%"=="8" (
        call :log_message "Java version 1.8 detected - proceeding with agent startup" "INFO"
    ) else (
        call :log_message "ERROR: Java version %java_version% is not supported. Please install Java 1.8 or higher." "ERROR"
        call :log_message "Current version %java_version% is below the minimum required version 1.8" "ERROR"
        
        call :show_error_alert "Java version %java_version% is not supported. Please install Java 1.8 or higher."
        goto exit_2
    )
) else (
    REM For major versions 9 and above, just check if it's >= 9
    if %major_version% geq 9 (
        call :log_message "Java version %java_version% detected - proceeding with agent startup" "INFO"
    ) else (
        call :log_message "ERROR: Java version %java_version% is not supported. Please install Java 1.8 or higher." "ERROR"
        
        call :show_error_alert "Java version %java_version% is not supported. Please install Java 1.8 or higher."
        goto exit_2
    )
)

REM Start the agent
call :log_message "Starting DQV/KTAC Agent with Java version %java_version%" "INFO"
call :log_message "Agent folder: %AGENT_FOLDER%" "INFO"
call :log_message "Log file: logs\agent\bootstrap-cli.log" "INFO"
call :log_message "Using Java: %JAVA_CMD%" "INFO"

"%FULL_JAVA_PATH%" -XX:+UseG1GC -XX:+HeapDumpOnOutOfMemoryError -jar bootstrap-agent.jar >> logs\agent\bootstrap-cli.log 2>&1
set "exit_code=%errorlevel%"

if %exit_code% neq 0 (
    call :log_message "Agent exited with error code %exit_code%" "ERROR"
) else (
    call :log_message "Agent completed successfully" "INFO"
)

goto exit_agent

REM Function to log messages with timestamp (placed at the end to avoid execution on script start)
:log_message
set "message=%~1"
set "level=%~2"
if "%level%"=="" set "level=INFO"
for /f "tokens=1-4 delims=/ " %%a in ('date /t') do set "date=%%a %%b %%c %%d"
for /f "tokens=1-2 delims=: " %%a in ('time /t') do set "time=%%a:%%b"
echo [%date% %time%] [%level%] %message% >> logs\agent\bootstrap-cli.log
echo [%level%] %message%
exit /b

REM Function to show error alerts with fallback chain
:show_error_alert
set "error_message=%~1"
if "%error_message%"=="" set "error_message=An error occurred. Please check the logs for details."

echo [DEBUG] Attempting to display error alert: "%error_message%"

REM Check if PowerShell is available
powershell -Command "Get-Host" >nul 2>&1
if %errorlevel% equ 0 (
    echo [DEBUG] PowerShell is available, trying MessageBox...
    REM Try to show error message using PowerShell
    powershell -Command "Add-Type -AssemblyName System.Windows.Forms; [System.Windows.Forms.MessageBox]::Show('%error_message%', 'DQV/KTAC Agent Error', [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Error)" >nul 2>&1
    if %errorlevel% equ 0 (
        call :log_message "Error message displayed using PowerShell" "INFO"
        echo [DEBUG] PowerShell MessageBox succeeded
        exit /b
    ) else (
        echo [DEBUG] PowerShell MessageBox failed with errorlevel: %errorlevel%
    )
) else (
    echo [DEBUG] PowerShell not available
)

REM Try msg command as fallback
echo [DEBUG] Trying msg command...
msg %username% "%error_message%" >nul 2>&1
if %errorlevel% equ 0 (
    call :log_message "Error message displayed using msg command" "INFO"
    echo [DEBUG] msg command succeeded
    exit /b
) else (
    echo [DEBUG] msg command failed with errorlevel: %errorlevel%
    call :log_message "Could not display message box. Press any key to continue..." "WARN"
    echo [DEBUG] Falling back to console pause
    pause >nul
)
exit /b


REM Exit points with appropriate error codes
:exit_1
    call :log_message "Exiting with error code 1 - Java not found" "ERROR"
    call :show_error_alert "Java is not installed or not found in PATH. Please install Java 1.8 or higher."
    if "%IMMEDIATE_EXIT%"=="1" (
        exit /b 1
    ) else (
        goto :end
    )

:exit_2
    call :log_message "Exiting with error code 2 - Java version not supported" "ERROR"
    call :show_error_alert "Java version %java_version% is not supported. Please install Java 1.8 or higher."
    if "%IMMEDIATE_EXIT%"=="1" (
        exit /b 2
    ) else (
        goto :end
    )

:exit_3
    call :log_message "Exiting with error code 3 - Java execution failed" "ERROR"
    call :show_error_alert "Java executable failed to run: %FULL_JAVA_PATH%. Please check your Java installation."
    if "%IMMEDIATE_EXIT%"=="1" (
        exit /b 3
    ) else (
        goto :end
    )

:exit_agent
    call :log_message "Exiting with agent error code %exit_code%" "INFO"
    if "%IMMEDIATE_EXIT%"=="1" (
        exit /b %exit_code%
    ) else (
        goto :end
    )

:end
REM In debug mode (IMMEDIATE_EXIT=0), script continues here after errors
REM In production mode (IMMEDIATE_EXIT=1), script exits immediately with error codes
