param(
    [string]$AgentDataRoot = (Join-Path $env:LOCALAPPDATA "ImageAnywhere\agent"),
    [string]$AgentInstallDirectory = (Join-Path $env:LOCALAPPDATA "Programs\ImageAnywhereAgent"),
    [string]$OutputJsonPath
)

Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"

$settingsPath = Join-Path $AgentDataRoot "agent-settings.json"
$agentExe = Join-Path $AgentInstallDirectory "agent\IAUWP.Agent.exe"
$maintenancePaused = $false
if ([string]::IsNullOrWhiteSpace($OutputJsonPath)) {
    $OutputJsonPath = Join-Path $PSScriptRoot "clinical-appliance-rollback-result.json"
}
if (-not (Test-Path -LiteralPath $settingsPath)) {
    throw "Agent settings were not found at '$settingsPath'. Nothing was changed."
}

try {
    $settings = Get-Content -LiteralPath $settingsPath -Raw | ConvertFrom-Json
}
catch {
    throw "Agent settings are not readable JSON. They were preserved unchanged."
}
if (-not $settings) {
    throw "Agent settings are empty. They were preserved unchanged."
}

$clientSupervisionProperty = $settings.PSObject.Properties["ClientSupervision"]
if (-not $clientSupervisionProperty -or $null -eq $clientSupervisionProperty.Value) {
    $result = [pscustomobject]@{
        SchemaVersion = 1
        Changed = $false
        MaintenancePaused = $maintenancePaused
        ClientSupervisionEnabled = $false
        SettingsPath = $settingsPath
        BackupPath = $null
        PreservedAgentPairingAndOtherSettings = $true
        PreservedUwpLocalState = $true
        StartupTaskRemoved = $false
        Guidance = "Supervision was already absent. The agent startup task and data were left unchanged."
    }
    $result | ConvertTo-Json -Depth 8 | Set-Content -LiteralPath $OutputJsonPath -Encoding UTF8
    $result | ConvertTo-Json -Depth 8
    exit 0
}

$clientSupervision = $clientSupervisionProperty.Value
if ($clientSupervision -isnot [pscustomobject]) {
    throw "ClientSupervision is not a JSON object. The settings file was preserved unchanged."
}
if (Test-Path -LiteralPath $agentExe) {
    & $agentExe --supervision-pause indefinite | Out-Null
    if ($LASTEXITCODE -ne 0) {
        throw "The agent could not enter maintenance pause. Settings were preserved unchanged."
    }
    $maintenancePaused = $true
}
$enabledProperty = $clientSupervision.PSObject.Properties["Enabled"]
if ($enabledProperty) {
    $enabledProperty.Value = $false
}
else {
    $clientSupervision | Add-Member -NotePropertyName "Enabled" -NotePropertyValue $false
}

$tempPath = $settingsPath + ".tmp-" + [Guid]::NewGuid().ToString("N")
$backupPath = $settingsPath + ".pre-clinical-appliance-rollback-" + (Get-Date -Format "yyyyMMdd-HHmmssfff") + ".bak"
$utf8NoBom = New-Object System.Text.UTF8Encoding($false)
[System.IO.File]::WriteAllText($tempPath, ($settings | ConvertTo-Json -Depth 20), $utf8NoBom)
try {
    [System.IO.File]::Replace($tempPath, $settingsPath, $backupPath)
}
finally {
    if (Test-Path -LiteralPath $tempPath) { Remove-Item -LiteralPath $tempPath -Force }
}

$result = [pscustomobject]@{
    SchemaVersion = 1
    Changed = $true
    MaintenancePaused = $maintenancePaused
    ClientSupervisionEnabled = $false
    SettingsPath = $settingsPath
    BackupPath = $backupPath
    PreservedAgentPairingAndOtherSettings = $true
    PreservedUwpLocalState = $true
    StartupTaskRemoved = $false
    Guidance = "Supervision was paused immediately when the installed agent was available and disabled for the next start. Remove the startup task or agent only under separate explicit approval."
}
$result | ConvertTo-Json -Depth 8 | Set-Content -LiteralPath $OutputJsonPath -Encoding UTF8
$result | ConvertTo-Json -Depth 8