param(
    [Parameter(Mandatory=$true)]
    [string]$Channel,

    [ValidateSet("release", "debug")]
    [string]$BuildType = "release"
)

$ErrorActionPreference = "Stop"

$AppId = "25653777174321448"
$Token = "OC|25653777174321448|b861e3eeaf58edf097812b5fe588dabb"
$OvrUtil = "$PSScriptRoot\ovr-platform-util.exe"
$BuildCountFile = "$PSScriptRoot\.buildcount"

# --- Increment build count ---
$buildCount = 1
if (Test-Path $BuildCountFile) {
    $buildCount = [int](Get-Content $BuildCountFile -Raw).Trim() + 1
}
Set-Content $BuildCountFile $buildCount -NoNewline
Write-Host "Build #$buildCount" -ForegroundColor Cyan

# --- Git version info ---
$versionName = (git describe --tags --abbrev=0 2>$null) -replace '^v', ''
if (-not $versionName) { $versionName = "0.1.0" }
$shortHash = git rev-parse --short HEAD 2>$null
if (-not $shortHash) { $shortHash = "unknown" }
$displayVersion = "$versionName+$buildCount.$shortHash"

Write-Host "Version: $displayVersion (versionCode=$buildCount)" -ForegroundColor Cyan

# --- Build APK ---
$task = if ($BuildType -eq "release") { ":app:assembleRelease" } else { ":app:assembleDebug" }
Write-Host "Building $BuildType APK..." -ForegroundColor Cyan
& "$PSScriptRoot\gradlew.bat" $task
if ($LASTEXITCODE -ne 0) { Write-Error "Build failed" }

$apk = "$PSScriptRoot\app\build\outputs\apk\$BuildType\app-$BuildType.apk"
if (-not (Test-Path $apk)) { Write-Error "APK not found: $apk" }

Write-Host "APK: $apk" -ForegroundColor Green

# --- Upload ---
Write-Host "Uploading to channel '$Channel'..." -ForegroundColor Cyan
& $OvrUtil upload-quest-build `
    --app-id $AppId `
    --token $Token `
    --apk $apk `
    --channel $Channel `
    --age-group MIXED_AGES `
    --notes "$displayVersion $BuildType build"

if ($LASTEXITCODE -ne 0) { Write-Error "Upload failed" }

Write-Host "Deployed $displayVersion ($BuildType) to '$Channel'" -ForegroundColor Green
