$ErrorActionPreference = 'Stop'
$log = Join-Path $env:ProgramData 'AssetManager\commands.log'
$clientLog = [System.Collections.Generic.List[string]]::new()
$JobResult = @{}
New-Item -ItemType Directory -Force -Path (Split-Path $log) | Out-Null
function Send-JobCallback([hashtable]$Data) {
  $json = $Data | ConvertTo-Json -Depth 8 -Compress
  $bodyBytes = [Text.Encoding]::UTF8.GetBytes($json)
  $lastError = $null
  for ($attempt = 1; $attempt -le 3; $attempt++) {
    try {
      Invoke-RestMethod -Method Post -Uri '{{CallbackUrl}}' -ContentType 'application/json; charset=utf-8' -Body $bodyBytes -TimeoutSec 60 | Out-Null
      if ($attempt -gt 1) { Write-JobLog ("Callback accepted on attempt $attempt of 3") }
      return
    } catch {
      $lastError = $_.Exception
      Write-JobLog ("Callback attempt $attempt of 3 failed: " + $_.Exception.Message)
      if ($attempt -lt 3) { Start-Sleep -Seconds (2 * $attempt) }
    }
  }
  throw ("Callback failed after 3 attempts: " + $lastError.Message)
}
function Write-JobLog([string]$Message) {
  $line = "$(Get-Date -Format o) job={{JobId}} $Message"
  $clientLog.Add($line)
  Add-Content -Path $log -Value $line -Encoding UTF8
  Write-Output $line
}
try {
  Write-JobLog 'Job started'
  try { Send-JobCallback @{status='running'; completed=$false; message='Job started on client'; log=($clientLog -join "`n")} } catch { Write-JobLog ("Initial callback failed: " + $_.Exception.Message) }
  # --- Eigene Befehle hier einfügen ---

  # --- Ende eigene Befehle ---
  Write-JobLog 'Job completed'
  $bodyData = @{status='success'; exit_code=0; completed=$true; message='Job completed'; log=($clientLog -join "`n")}
  if ($JobResult -is [System.Collections.IDictionary]) { foreach ($key in $JobResult.Keys) { $bodyData[$key] = $JobResult[$key] } }
  $body = $bodyData | ConvertTo-Json -Depth 8 -Compress
  Send-JobCallback $bodyData
} catch {
  Write-JobLog ("Job failed: " + $_.Exception.Message)
  $body = @{status='failed'; exit_code=1; completed=$true; message=$_.Exception.Message; log=($clientLog -join "`n"); stderr=($_ | Out-String)} | ConvertTo-Json -Compress
  try { Send-JobCallback @{status='failed'; exit_code=1; completed=$true; message=$_.Exception.Message; log=($clientLog -join "`n"); stderr=($_ | Out-String)} } catch {}
  exit 1
}
