@echo off
setlocal enabledelayedexpansion

echo ================================
echo GDScript Test Runner
echo ================================
echo.

REM Check if Godot is available
godot --version >nul 2>&1
if !errorlevel! neq 0 (
    echo ERROR: Godot is not installed or not in PATH
    echo.
    echo Installation instructions:
    echo 1. Download Godot from https://godotengine.org/download
    echo 2. Add Godot executable to your PATH environment variable
    echo 3. Or place godot.exe in this project directory
    echo 4. Restart your command prompt
    echo 5. Run this script again
    echo.
    pause
    exit /b 1
)

echo Scanning for test files in tests\ directory...

set total_tests=0
set failed_tests=0

echo.
echo Discovered test files:

call :discover_tests "tests" ""
call :discover_tests "tests\unit" "Unit: "
call :discover_tests "tests\integration" "Integration: "

echo.
echo Starting test execution...
echo.

call :run_tests "tests" ""
call :run_tests "tests\unit" "Unit: "
call :run_tests "tests\integration" "Integration: "

set /a passed_tests=total_tests-failed_tests

echo ================================
echo Test Execution Summary
echo ================================
echo Total Tests Run: !total_tests!
echo Tests Passed: !passed_tests!
echo Tests Failed: !failed_tests!

if !failed_tests! equ 0 (
    echo ✅ ALL TESTS PASSED!
) else (
    echo ❌ !failed_tests! TEST(S) FAILED
)

pause
goto :eof

:discover_tests
set "test_dir=%~1"
set "prefix=%~2"
if exist "%test_dir%\" (
    for %%f in ("%test_dir%\test_*.gd") do (
        call :format_test_name "%%~nf" test_name
        echo   %prefix%!test_name!: %%f
    )
)
goto :eof

:run_tests
set "test_dir=%~1"
set "prefix=%~2"
if exist "%test_dir%\" (
    for %%f in ("%test_dir%\test_*.gd") do (
        call :format_test_name "%%~nf" test_name
        call :run_single_test "%%f" "%prefix%!test_name!"
    )
)
goto :eof

:format_test_name
set "filename=%~1"
set "result=%filename:test_=%"
set "%~2=%result:_= %"
goto :eof

:run_single_test
set "test_file=%~1"
set "test_name=%~2"

echo.
echo === %test_name% ===
echo Running: %test_file%

REM Run the test and capture the exit code
godot --headless --script "%test_file%" >temp_test_output.txt 2>&1
set test_exit_code=!errorlevel!

REM Display results based on exit code
if !test_exit_code! equ 0 (
    echo PASSED: %test_name%
) else (
    echo FAILED: %test_name%
    set /a failed_tests+=1
)
set /a total_tests+=1

REM Clean up temporary file
if exist temp_test_output.txt del temp_test_output.txt

echo.
goto :eof