param(
    [string]$EmmaHome = 'C:\Emma\current',
    [string]$UpdateUrl = $env:EMMA_UPDATE_URL
)

$ErrorActionPreference = 'Stop'
$agentExe = Join-Path $EmmaHome 'runtime\emma-agent.exe'
$emmaBase = Split-Path $EmmaHome -Parent

if (-not $UpdateUrl) {
    $configPath = Join-Path $EmmaHome 'config.json'
    if (Test-Path $configPath) {
        $cfg = Get-Content $configPath -Raw | ConvertFrom-Json
        if ($cfg.updateServerUrl) { $UpdateUrl = [string]$cfg.updateServerUrl }
    }
}

if (-not $UpdateUrl) {
    Write-Warning 'Kein Update-Server konfiguriert (EMMA_UPDATE_URL oder config.json).'
    exit 0
}

# Agent appends /latest.json; accept accidental full manifest URLs.
$UpdateUrl = $UpdateUrl.Trim().TrimEnd('/')
if ($UpdateUrl -match '/latest\.json$') {
    $UpdateUrl = $UpdateUrl -replace '/latest\.json$', ''
}

if (-not (Test-Path $agentExe)) {
    throw "emma-agent.exe nicht gefunden: $agentExe"
}

Write-Host "Emma Update: $UpdateUrl (home=$EmmaHome, base=$emmaBase)"
$env:EMMA_HOME = $EmmaHome
& $agentExe update --url $UpdateUrl --base $emmaBase
if ($LASTEXITCODE -ne 0) {
    throw "emma-agent update failed (exit $LASTEXITCODE) for $UpdateUrl"
}
