[CmdletBinding()]
param(
    [switch]$Launch
)

$ErrorActionPreference = 'Stop'
$ProjectRoot = (Resolve-Path -LiteralPath (Split-Path -Parent $MyInvocation.MyCommand.Path)).Path
$Apk = Join-Path (Resolve-Path -LiteralPath (Join-Path $ProjectRoot '..')).Path 'dist\KIMQuestRemote.apk'
$Adb = if ($env:ANDROID_SDK_ROOT -and (Test-Path -LiteralPath "$env:ANDROID_SDK_ROOT\platform-tools\adb.exe")) {
    "$env:ANDROID_SDK_ROOT\platform-tools\adb.exe"
} else {
    (Get-Command adb -ErrorAction Stop).Source
}

if (-not (Test-Path -LiteralPath $Apk)) {
    throw "APK not found. Run .\build.ps1 first: $Apk"
}

$DeviceLines = & $Adb devices
$Devices = @($DeviceLines | Where-Object { $_ -match '^([^\s]+)\s+device$' })
$Unauthorized = @($DeviceLines | Where-Object { $_ -match '\s+unauthorized$' })

if ($Unauthorized.Count -gt 0) {
    throw 'Quest is visible but USB debugging is not approved. Put on the headset and approve the USB debugging prompt.'
}
if ($Devices.Count -eq 0) {
    throw 'No authorized Quest is connected. Enable Developer Mode, connect USB, and approve USB debugging in the headset.'
}
if ($Devices.Count -gt 1) {
    throw 'More than one ADB device is connected. Disconnect the other device before installing.'
}

Write-Host "Installing $Apk ..."
& $Adb install -r $Apk
if ($LASTEXITCODE -ne 0) { throw 'ADB installation failed.' }

if ($Launch) {
    & $Adb shell am start -n com.kim.questremote/.MainActivity
    if ($LASTEXITCODE -ne 0) { throw 'APK installed, but launch command failed.' }
}

Write-Host 'INSTALL_PASS'
Write-Host 'Open KIM Quest Remote from the Quest app library under Unknown Sources.'

