@echo off
SETLOCAL EnableDelayedExpansion

:: 设置 UTF-8 代码页以支持中文显示
chcp 65001 > nul

:: 获取项目根目录
for %%I in ("%~dp0.") do set "PROJECT_DIR=%%~fI"

:: 1. 强制终止所有Java进程（Gradle相关）
echo Terminating processes...
taskkill /f /im java.exe 2>nul
taskkill /f /im gradlew.exe 2>nul
timeout /t 2 /nobreak >nul

:: 修复后的Flutter构建脚本
echo Running flutter clean...
call flutter clean
if !ERRORLEVEL! neq 0 (
    echo flutter clean failed with error: !ERRORLEVEL!
    pause
    exit /b 1
)

:: 3. 强制删除构建目录（带重试机制）
echo Removing residual files
call :ForceDelete "build"
call :ForceDelete ".dart_tool"
call :ForceDelete "pubspec.lock"

echo Running flutter pub get...
call flutter pub get
if !ERRORLEVEL! neq 0 (
    echo flutter pub get failed with error: !ERRORLEVEL!
    pause
    exit /b 1
)

echo Running build_runner...
call flutter packages pub run build_runner build --delete-conflicting-outputs
if !ERRORLEVEL! neq 0 (
    echo build_runner failed with error: !ERRORLEVEL!
    pause
    exit /b 1
)

echo Building release APK...
call flutter build apk --release
if !ERRORLEVEL! neq 0 (
    echo APK build failed with error: !ERRORLEVEL!
    pause
    exit /b 1
)

:: 新增：打开APK所在文件夹  
echo Opening APK directory  
if exist "build\app\outputs\flutter-apk\" (
    explorer "build\app\outputs\flutter-apk\"
) else (
    echo APK directory does not exist
)

echo.
echo All steps completed successfully!
echo APK file generated at: %PROJECT_DIR%\build\app\outputs\flutter-apk\
echo.
timeout /t 3 /nobreak >nul
exit /b 0
 
:: 函数区 -------------------------------------------------
:ForceDelete
setlocal
set "target=%~1"
set "max_retries=3"
set "retry_delay=1"

:: 检查目标是否存在
if not exist "%target%" (
    endlocal
    goto :eof
)

:: 尝试多次删除
for /l %%i in (1,1,%max_retries%) do (
    echo Attempting to delete %target% (try %%i of %max_retries%)
    
    :: 先尝试删除文件
    del /f /q /s "%target%\*" 2>nul
    :: 再尝试删除目录
    rmdir /s /q "%target%" 2>nul
    
    :: 检查是否删除成功
    if not exist "%target%" (
        echo Successfully deleted %target%
        endlocal
        goto :eof
    )
    
    :: 如果未成功，等待后重试
    if %%i lss %max_retries% (
        timeout /t %retry_delay% /nobreak >nul
        set /a retry_delay*=2  :: 指数退避策略
    )
)

:: 如果所有尝试都失败
echo Warning: Could not completely delete %target%, some files may be in use
endlocal
goto :eof