# Install debug APKs to connected Android device via adb
$ErrorActionPreference = "Stop"
$ProjectRoot = Split-Path -Parent $PSScriptRoot
$appApk = Join-Path $ProjectRoot "app\build\outputs\apk\debug\app-debug.apk"
$xposedApk = Join-Path $ProjectRoot "xposed-module\build\outputs\apk\debug\xposed-module-debug.apk"

if (-not (Test-Path $appApk)) {
    Write-Host "App APK not found. Run scripts\build-debug.ps1 first." -ForegroundColor Red
    exit 1
}

$sdk = "C:\Users\Administrator\AppData\Local\Android\Sdk"
$adb = Join-Path $sdk "platform-tools\adb.exe"
if (-not (Test-Path $adb)) {
    Write-Host "adb not found at $adb" -ForegroundColor Red
    exit 1
}

& $adb devices
Write-Host "Installing app: $appApk ..."
& $adb shell settings put global verifier_verify_adb_installs 0 2>$null
& $adb install -r -t -g $appApk
if ($LASTEXITCODE -ne 0) {
    Write-Host "Retry install with --bypass-low-target-sdk-block ..."
    & $adb install -r -t -g --bypass-low-target-sdk-block $appApk
}
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }

if (Test-Path $xposedApk) {
    Write-Host "Installing xposed module: $xposedApk ..."
    & $adb install -r -t -g $xposedApk
    if ($LASTEXITCODE -ne 0) {
        & $adb install -r -t -g --bypass-low-target-sdk-block $xposedApk
    }
    if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
} else {
    Write-Host "Xposed APK not found, skipped." -ForegroundColor Yellow
}

Write-Host "Install OK." -ForegroundColor Green
Write-Host "Remember to enable the module in LSPosed and scope Telegram + notiMessage."
