param(
  [Parameter(Mandatory=$true)][int]$AgentPid,
  [Parameter(Mandatory=$true)][string]$ZipPath,
  [Parameter(Mandatory=$true)][string]$InstallDir
)
$ErrorActionPreference = 'Stop'
try { [Console]::OutputEncoding = [Text.Encoding]::UTF8; $OutputEncoding = [Text.Encoding]::UTF8 } catch {}
$updaterLog = Join-Path $InstallDir 'updater.log'
$launcherCmd = Join-Path $InstallDir 'ABRIR_AGENT.cmd'
$iconPath = Join-Path $InstallDir 'flowinsta-agent-icon.ico'
$statusPath = Join-Path $InstallDir 'update-status.txt'
function Write-UpdaterLog([string]$line) {
  try { Add-Content -LiteralPath $updaterLog -Value "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') $line" -Encoding UTF8 } catch {}
}
function New-AgentShortcut([string]$shortcutPath, [string]$targetPath) {
  try {
    $shell = New-Object -ComObject WScript.Shell
    $shortcut = $shell.CreateShortcut($shortcutPath)
    $shortcut.TargetPath = $targetPath
    $shortcut.WorkingDirectory = Split-Path -Parent $targetPath
    $shortcut.WindowStyle = 1
    $shortcut.Description = 'Abrir FlowInsta BR Agent'
    if (Test-Path -LiteralPath $iconPath) { $shortcut.IconLocation = $iconPath }
    $shortcut.Save()
  } catch {
    Write-UpdaterLog "Falha ao recriar atalho: $($_.Exception.Message)"
  }
}
try {
  Write-UpdaterLog "Iniciando atualização. Aguardando processo antigo (PID $AgentPid) encerrar..."
  Set-Content -LiteralPath $statusPath -Value 'pending' -Encoding ASCII
  try { Wait-Process -Id $AgentPid -Timeout 30 -ErrorAction SilentlyContinue } catch {}
  $staging = Join-Path $env:TEMP "flowinsta-agent-update-$([guid]::NewGuid().ToString('N'))"
  New-Item -ItemType Directory -Path $staging -Force | Out-Null
  Expand-Archive -LiteralPath $ZipPath -DestinationPath $staging -Force
  Copy-Item -Path (Join-Path $staging '*') -Destination $InstallDir -Recurse -Force
  Remove-Item -LiteralPath $staging -Recurse -Force
  Remove-Item -LiteralPath $ZipPath -Force -ErrorAction SilentlyContinue
  if (Test-Path -LiteralPath $launcherCmd) {
    $desktopCmd = Join-Path ([Environment]::GetFolderPath('Desktop')) 'FlowInsta BR Agent.cmd'
    $desktopLnk = Join-Path ([Environment]::GetFolderPath('Desktop')) 'FlowInsta BR Agent.lnk'
    [IO.File]::WriteAllText($desktopCmd, "@echo off`r`nchcp 65001 >nul`r`ncall `"$launcherCmd`"`r`n", [Text.Encoding]::ASCII)
    New-AgentShortcut $desktopLnk $launcherCmd
  }
  Set-Content -LiteralPath $statusPath -Value 'done' -Encoding ASCII
  Write-UpdaterLog "Arquivos atualizados. Launcher vai reabrir o Agent."
  Write-UpdaterLog "Atualização concluída com sucesso."
} catch {
  try { Set-Content -LiteralPath $statusPath -Value "failed $($_.Exception.Message)" -Encoding UTF8 } catch {}
  Write-UpdaterLog "ERRO na atualização: $($_.Exception.Message)"
  try {
    Add-Type -AssemblyName System.Windows.Forms
    [System.Windows.Forms.MessageBox]::Show(
      "A atualização do FlowInsta BR Agent falhou: $($_.Exception.Message)`n`nAbra o Agent manualmente (ABRIR_AGENT.cmd) e avise o suporte. Detalhes em: $updaterLog",
      'FlowInsta BR Agent - Falha na atualização'
    ) 2>$null
  } catch {}
}

