param(
    [Parameter(Position = 0)]
    [string]$Serial,
    [switch]$RemoveCompatibleComponents,
    [switch]$RemoveSteshApps,
    [switch]$RemoveSmbClient,
    [switch]$NonInteractive
)

$ErrorActionPreference = "Stop"
$kitRoot = Split-Path -Parent $MyInvocation.MyCommand.Path
$platformTools = Join-Path $kitRoot "platform-tools"
$adb = Join-Path $platformTools "adb.exe"
if (-not (Test-Path -LiteralPath $adb)) {
    throw "Portable adb.exe is missing from the kit: $adb. Extract the complete ZIP before starting Rollback.cmd."
}
Get-ChildItem -LiteralPath $platformTools -File -ErrorAction SilentlyContinue |
    Unblock-File -ErrorAction SilentlyContinue
if ([string]::IsNullOrWhiteSpace($Serial)) {
    if ($NonInteractive) { throw "-Serial is required in non-interactive mode" }
    $Serial = Read-Host "RT-G2 address (for example 192.168.1.50 or 192.168.1.50:5555)"
}
$Serial = $Serial.Trim()
if ($Serial -match '^\d{1,3}(\.\d{1,3}){3}$') { $Serial = "${Serial}:5555" }
if ($Serial -notmatch '^[^\s:]+:\d{1,5}$') { throw "Invalid device address: '$Serial'" }
$connectOutput = (& $adb connect $Serial 2>&1 | Out-String).Trim()
Write-Host $connectOutput
$baselinePath = Join-Path $kitRoot "rtg2-baseline.json"
if (-not (Test-Path -LiteralPath $baselinePath)) { throw "Baseline not found: $baselinePath" }
$baseline = Get-Content -LiteralPath $baselinePath -Raw | ConvertFrom-Json

if ((& $adb -s $Serial get-state).Trim() -ne "device") { throw "ADB device is not connected/authorized: $Serial" }
if ((& $adb -s $Serial shell getprop ro.product.model).Trim() -ne "RT-G2") { throw "Rollback target is not RT-G2" }

foreach ($property in $baseline.global.PSObject.Properties) {
    if ($property.Value -eq "null" -or [string]::IsNullOrWhiteSpace([string]$property.Value)) {
        & $adb -s $Serial shell settings delete global $property.Name | Out-Null
    } else {
        & $adb -s $Serial shell settings put global $property.Name ([string]$property.Value) | Out-Null
    }
}
if ($baseline.enabledAccessibilityServices -eq "null" -or [string]::IsNullOrWhiteSpace($baseline.enabledAccessibilityServices)) {
    & $adb -s $Serial shell settings delete secure enabled_accessibility_services | Out-Null
} else {
    & $adb -s $Serial shell settings put secure enabled_accessibility_services $baseline.enabledAccessibilityServices | Out-Null
}
& $adb -s $Serial shell settings put secure accessibility_enabled $baseline.accessibilityEnabled | Out-Null
& $adb -s $Serial shell am start -W -n info.technozon.steshmodifier/.RollbackActivity | Out-Null
if ($baseline.PSObject.Properties.Name -contains 'homeActivity' -and -not [string]::IsNullOrWhiteSpace($baseline.homeActivity)) {
    & $adb -s $Serial shell cmd package set-home-activity $baseline.homeActivity | Out-Null
}
& $adb -s $Serial uninstall info.technozon.steshmodifier | Out-Host

if ($RemoveCompatibleComponents) {
    "com.jamal2367.videoinfooverlay","com.jamal2367.advancedreboot","com.jamal2367.cputemperature" |
        ForEach-Object { & $adb -s $Serial uninstall $_ | Out-Host }
}
if ($RemoveSteshApps) {
    "ua.tvsearch.app","ua.com.technozon.tvwebview","ua.com.technozon.tvboxeswebview" |
        ForEach-Object { & $adb -s $Serial uninstall $_ | Out-Host }
}
if ($RemoveSmbClient) {
    & $adb -s $Serial uninstall info.technozon.rtg2smbclient | Out-Host
}
Write-Host "Rollback complete. Original settings were restored from $baselinePath"
