@echo off
setlocal EnableExtensions EnableDelayedExpansion

set "SCRIPT_DIR=%~dp0"
set "ANDROID_DIR=%SCRIPT_DIR%android"
set "APK_OUTPUT=%ANDROID_DIR%\app\build\outputs\apk\release\app-release.apk"
set "BUNDLE_OUTPUT=%ANDROID_DIR%\app\build\outputs\bundle\release\app-release.aab"

cd /d "%SCRIPT_DIR%"

echo === TeamSpeak Mobile Release Build ===
echo.

REM 1. Build the Go bridge and AAR with the required Android linker flags.
echo [1/3] Building Go bridge and Android AAR...
call "%SCRIPT_DIR%build.bat"
if errorlevel 1 (
    echo ERROR: Go bridge/AAR build failed.
    exit /b 1
)

REM 2. Build the signed release APK and Play Store bundle.
echo.
echo [2/3] Building release APK and AAB...
if not exist "%ANDROID_DIR%\gradlew.bat" (
    echo ERROR: gradlew.bat not found in "%ANDROID_DIR%".
    exit /b 1
)

REM Stop old Gradle daemons before building. Do not run clean here: Android Studio,
REM antivirus, or a previous Gradle daemon can temporarily lock app\build files.
call "%ANDROID_DIR%\gradlew.bat" -p "%ANDROID_DIR%" --stop >nul 2>&1
call "%ANDROID_DIR%\gradlew.bat" -p "%ANDROID_DIR%" assembleRelease bundleRelease
if errorlevel 1 (
    echo ERROR: Release build failed.
    echo If app\build is locked, close Android Studio/Explorer windows using it,
    echo then run: android\gradlew.bat -p android --stop
    echo Check android/app/build.gradle.kts signingConfigs and Gradle properties.
    exit /b 1
)

REM 3. Report generated artifacts.
echo.
echo [3/3] Release build complete.
if exist "%APK_OUTPUT%" echo APK:    %APK_OUTPUT%
if exist "%BUNDLE_OUTPUT%" echo AAB:    %BUNDLE_OUTPUT%
if not exist "%APK_OUTPUT%" if not exist "%BUNDLE_OUTPUT%" (
    echo ERROR: No release artifact was generated.
    exit /b 1
)

echo.
echo Note: Release signing must be configured in android/app/build.gradle.kts.
echo Keep the keystore and passwords outside the repository.
exit /b 0
