# Launch MariBank Singapore (not PH SeaBank)
param(
    [switch]$ClearData,
    [switch]$StopPh,
    [switch]$ColdStart,
    [int]$WaitSeconds = 0
)

$ErrorActionPreference = "Stop"
$PkgSg = "sg.com.maribankmobile.digitalbank"
$PkgPh = "ph.seabank.seabank"
$Activity = "com.shopee.bke.digitalbank.ui.MainActivity"

function Resolve-AdbPath {
    $candidates = @(
        (Join-Path $env:LOCALAPPDATA "Android\Sdk\platform-tools\adb.exe"),
        "C:\Users\Administrator\AppData\Local\Android\Sdk\platform-tools\adb.exe"
    )
    foreach ($path in $candidates) {
        if (Test-Path $path) { return $path }
    }
    $cmd = Get-Command adb -ErrorAction SilentlyContinue
    if ($cmd) { return $cmd.Source }
    return $null
}

$adb = Resolve-AdbPath
if (-not $adb) {
    Write-Host "adb not found." -ForegroundColor Red
    exit 1
}

$devices = & $adb devices 2>&1 | Where-Object { $_ -match "\tdevice$" }
if (-not $devices) {
    Write-Host "No authorized adb device." -ForegroundColor Red
    exit 1
}

Write-Host "=== Launch MariBank SINGAPORE ===" -ForegroundColor Cyan
Write-Host "Package: $PkgSg (v3.2.2)"
Write-Host ""
Write-Host "[Required] After Xposed module update: LSPosed -> scope SG pkg -> re-optimize / force-stop / launch" -ForegroundColor Yellow
Write-Host "         Without soft reboot, old hooks may cause BLANK-PAGE white screen." -ForegroundColor Yellow
Write-Host ""
Write-Host "Package: sg.com.maribankmobile.digitalbank (NOT ph.seabank.seabank)" -ForegroundColor Yellow
Write-Host ""

if ($StopPh) {
    & $adb shell am force-stop $PkgPh | Out-Null
}

if ($ClearData) {
    Write-Host "Clearing SG app data..."
    & $adb shell pm clear $PkgSg | Out-Null
}

if ($ColdStart) {
    Write-Host "Cold start: force-stop SG (first screen may stay white 30-60s)" -ForegroundColor Cyan
    & $adb shell am force-stop $PkgSg | Out-Null
    Start-Sleep -Seconds 2
} else {
    Write-Host "Warm start (recommended). Use -ColdStart for cold start." -ForegroundColor Cyan
}

& $adb shell am start -n "$PkgSg/$Activity"

Write-Host ""
Write-Host "MariBank SG launched." -ForegroundColor Green
Write-Host "RN may show BLANK-PAGE for ~25-45s before welcome screen."
Write-Host "If white screen > 1 min: LSPosed soft reboot SG, then retry -ColdStart"
Write-Host "Verify API: adb logcat -d | Select-String api.maribank.com.sg"

if ($WaitSeconds -gt 0) {
    Write-Host ""
    Write-Host "Waiting ${WaitSeconds}s for UI..." -ForegroundColor Cyan
    Start-Sleep -Seconds $WaitSeconds
    & $adb shell uiautomator dump /sdcard/ui_launch_check.xml 2>&1 | Out-Null
    $prevEap = $ErrorActionPreference
    $ErrorActionPreference = "Continue"
    & $adb pull /sdcard/ui_launch_check.xml "$env:TEMP\ui_launch_check.xml" 2>&1 | Out-Null
    $ErrorActionPreference = $prevEap
    if (Test-Path "$env:TEMP\ui_launch_check.xml") {
        $xml = Get-Content "$env:TEMP\ui_launch_check.xml" -Raw
        $blank = $xml -match "BLANK-PAGE"
        Write-Host ("BLANK-PAGE=" + $blank)
    }
}
