@echo off
setlocal enabledelayedexpansion

echo ========================================
echo   TSS Party Android APK Builder
echo ========================================
echo.

:: Check if gradlew exists
if not exist "gradlew.bat" (
    echo [ERROR] gradlew.bat not found!
    echo Please run this script from the service-party-android directory.
    pause
    exit /b 1
)

:: Check and create local.properties if needed
if not exist "local.properties" (
    echo [INFO] local.properties not found, attempting to detect Android SDK...

    :: Try common SDK locations
    set SDK_FOUND=0

    :: Check ANDROID_HOME environment variable first
    if defined ANDROID_HOME (
        :: Remove any surrounding quotes from ANDROID_HOME
        set "ANDROID_HOME_CLEAN=!ANDROID_HOME:"=!"
        if exist "!ANDROID_HOME_CLEAN!\platform-tools" (
            set "SDK_PATH_CLEAN=!ANDROID_HOME_CLEAN:\=/!"
            echo sdk.dir=!SDK_PATH_CLEAN!> local.properties
            echo [INFO] Created local.properties with ANDROID_HOME: !ANDROID_HOME_CLEAN!
            set SDK_FOUND=1
        )
    )

    :: Try common Windows locations
    if !SDK_FOUND!==0 (
        for %%P in (
            "%LOCALAPPDATA%\Android\Sdk"
            "%USERPROFILE%\AppData\Local\Android\Sdk"
            "C:\Android\Sdk"
            "C:\Android"
            "C:\Users\%USERNAME%\Android\Sdk"
        ) do (
            if exist "%%~P\platform-tools" (
                set "SDK_PATH=%%~P"
                set "SDK_PATH=!SDK_PATH:\=/!"
                echo sdk.dir=!SDK_PATH!> local.properties
                echo [INFO] Created local.properties with SDK path: %%~P
                set SDK_FOUND=1
                goto :sdk_found
            )
        )
    )

    :sdk_found
    if !SDK_FOUND!==0 (
        echo [ERROR] Android SDK not found!
        echo.
        echo Please do one of the following:
        echo   1. Set ANDROID_HOME environment variable to your SDK path
        echo   2. Create local.properties file with: sdk.dir=C:/path/to/android/sdk
        echo   3. Install Android Studio which includes the SDK
        echo.
        echo Common SDK locations:
        echo   - %LOCALAPPDATA%\Android\Sdk
        echo   - C:\Android\Sdk
        echo.
        pause
        exit /b 1
    )
)

echo [INFO] Using SDK from local.properties
type local.properties
echo.

:: Parse rebuild argument early - must happen BEFORE checking tsslib.aar
set REBUILD_REQUESTED=0
if "%1"=="rebuild" (
    set REBUILD_REQUESTED=1
    echo [INFO] Rebuild requested - deleting tsslib.aar to recompile Go code...
    if exist "app\libs\tsslib.aar" (
        del /f "app\libs\tsslib.aar"
        echo [INFO] tsslib.aar deleted, will be rebuilt
    ) else (
        echo [INFO] tsslib.aar not found, will be built fresh
    )
    echo.
)

:: Check and build tsslib.aar if needed
if not exist "app\libs\tsslib.aar" (
    echo [INFO] tsslib.aar not found, attempting to build TSS library...
    echo.

    :: Check if Go is installed
    where go >nul 2>nul
    if !errorlevel! neq 0 (
        echo [ERROR] Go is not installed or not in PATH!
        echo Please install Go from https://golang.org/dl/
        pause
        exit /b 1
    )

    :: Get GOPATH for bin directory
    for /f "tokens=*" %%G in ('go env GOPATH') do set "GOPATH_DIR=%%G"
    if not defined GOPATH_DIR set "GOPATH_DIR=%USERPROFILE%\go"
    set "GOBIN_DIR=!GOPATH_DIR!\bin"

    :: Add GOPATH/bin to PATH if not already there
    echo !PATH! | findstr /i /c:"!GOBIN_DIR!" >nul 2>nul
    if !errorlevel! neq 0 (
        echo [INFO] Adding !GOBIN_DIR! to PATH...
        set "PATH=!PATH!;!GOBIN_DIR!"
    )

    :: Show Go version
    for /f "tokens=3" %%V in ('go version') do set "GO_VERSION=%%V"
    echo [INFO] Go version: !GO_VERSION!

    :: Get the tsslib directory path (inside service-party-android)
    set "TSSLIB_DIR=tsslib"

    if not exist "!TSSLIB_DIR!\go.mod" (
        echo [ERROR] TSS library source not found at !TSSLIB_DIR!
        echo Please ensure the tsslib source code exists.
        pause
        exit /b 1
    )

    :: IMPORTANT: Add gomobile dependency to go.mod (official recommended step)
    echo [INFO] Adding gomobile dependency to go.mod...
    pushd "!TSSLIB_DIR!"
    go get -d golang.org/x/mobile/cmd/gomobile
    if !errorlevel! neq 0 (
        echo [WARNING] go get gomobile failed, continuing anyway...
    )
    popd

    :: Install gomobile
    echo [INFO] Installing gomobile...
    go install golang.org/x/mobile/cmd/gomobile@latest
    if !errorlevel! neq 0 (
        echo [ERROR] Failed to install gomobile!
        pause
        exit /b 1
    )

    :: Verify gomobile exists
    if not exist "!GOBIN_DIR!\gomobile.exe" (
        echo [ERROR] gomobile was not installed correctly!
        echo Please check your Go installation and GOPATH.
        echo Expected location: !GOBIN_DIR!\gomobile.exe
        pause
        exit /b 1
    )

    echo [INFO] Initializing gomobile...
    "!GOBIN_DIR!\gomobile.exe" init
    if !errorlevel! neq 0 (
        echo [WARNING] gomobile init failed, but continuing...
    )

    echo [INFO] Building tsslib.aar with gomobile...
    pushd "!TSSLIB_DIR!"

    :: Build the AAR
    :: Use -androidapi 21 to ensure compatibility with modern NDK
    "!GOBIN_DIR!\gomobile.exe" bind -target=android -androidapi 21 -o "..\app\libs\tsslib.aar" .
    if !errorlevel! neq 0 (
        echo [ERROR] gomobile bind failed!
        popd
        pause
        exit /b 1
    )

    popd

    if exist "app\libs\tsslib.aar" (
        echo [SUCCESS] tsslib.aar built successfully!
        for %%F in ("app\libs\tsslib.aar") do echo   Size: %%~zF bytes
    ) else (
        echo [ERROR] tsslib.aar was not created!
        pause
        exit /b 1
    )
    echo.
) else (
    echo [INFO] tsslib.aar found, skipping TSS library build
    for %%F in ("app\libs\tsslib.aar") do echo   Size: %%~zF bytes
    echo.
)

:: Parse command line arguments
set BUILD_TYPE=all
if "%1"=="debug" set BUILD_TYPE=debug
if "%1"=="release" set BUILD_TYPE=release
if "%1"=="clean" set BUILD_TYPE=clean
if "%1"=="rebuild" set BUILD_TYPE=rebuild
if "%1"=="help" goto :show_help

:: Handle rebuild - aar deletion already done above, just set build type
if "%BUILD_TYPE%"=="rebuild" (
    set BUILD_TYPE=all
)

:: Show build type
echo Build type: %BUILD_TYPE%
echo.

:: Clean build
if "%BUILD_TYPE%"=="clean" (
    echo [1/1] Cleaning build files...
    call gradlew.bat clean --no-daemon
    if !errorlevel! neq 0 (
        echo [ERROR] Clean failed!
        pause
        exit /b 1
    )
    echo.
    echo [SUCCESS] Clean completed!
    goto :end
)

:: Build Debug APK
if "%BUILD_TYPE%"=="debug" goto :build_debug
if "%BUILD_TYPE%"=="all" goto :build_debug
goto :check_release

:build_debug
echo [1/2] Building Debug APK...
call gradlew.bat assembleDebug --no-daemon
if !errorlevel! neq 0 (
    echo [ERROR] Debug build failed!
    pause
    exit /b 1
)
echo [SUCCESS] Debug APK built successfully!
echo   Location: app\build\outputs\apk\debug\app-debug.apk
echo.

:check_release
if "%BUILD_TYPE%"=="debug" goto :show_results

:: Build Release APK
:build_release
echo [2/2] Building Release APK...
call gradlew.bat assembleRelease --no-daemon
if !errorlevel! neq 0 (
    echo [ERROR] Release build failed!
    pause
    exit /b 1
)
echo [SUCCESS] Release APK built successfully!
echo   Location: app\build\outputs\apk\release\app-release.apk
echo.

:show_results
echo ========================================
echo   Build Results
echo ========================================
echo.

:: Check and show Debug APK
if exist "app\build\outputs\apk\debug\app-debug.apk" (
    for %%F in ("app\build\outputs\apk\debug\app-debug.apk") do (
        echo [DEBUG APK]
        echo   Path: %%~fF
        echo   Size: %%~zF bytes
    )
    echo.
)

:: Check and show Release APK
if exist "app\build\outputs\apk\release\app-release.apk" (
    for %%F in ("app\build\outputs\apk\release\app-release.apk") do (
        echo [RELEASE APK]
        echo   Path: %%~fF
        echo   Size: %%~zF bytes
    )
    echo.
)

echo ========================================
echo   Build completed successfully!
echo ========================================
goto :end

:show_help
echo.
echo Usage: build-apk.bat [option]
echo.
echo Options:
echo   debug    - Build debug APK only
echo   release  - Build release APK only
echo   all      - Build both debug and release APKs (default)
echo   clean    - Clean Gradle build files
echo   rebuild  - Delete tsslib.aar and rebuild everything (use after Go code changes)
echo   help     - Show this help message
echo.
echo Examples:
echo   build-apk.bat           - Build both APKs
echo   build-apk.bat debug     - Build debug APK only
echo   build-apk.bat release   - Build release APK only
echo   build-apk.bat clean     - Clean Gradle project
echo   build-apk.bat rebuild   - Recompile Go code and build APKs
echo.

:end
echo.
pause
