param (
    [Parameter(Mandatory=$true)]
    [string]$DownloadUrl,
    
    [Parameter(Mandatory=$true)]
    [string]$InstallDirectory
)

$ErrorActionPreference = "Stop"
$LogFile = Join-Path $InstallDirectory "update_process.log"

function Log {
    param([string]$message)
    $stamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    "[$stamp] $message" | Out-File -Append -FilePath $LogFile
    Write-Host "[$stamp] $message"
}

Log "Starting OTA Update Protocol from $DownloadUrl"
Log "Target Directory: $InstallDirectory"

# 1. Download Payload
$ZipPath = Join-Path $env:TEMP "ThrallAgentUpdate_$((Get-Date).Ticks).zip"
Log "Downloading payload to $ZipPath..."
Invoke-WebRequest -Uri $DownloadUrl -OutFile $ZipPath

# 2. Terminate the active agent
Log "Terminating running Agent instances..."
Get-Process -Name "Thrall.Radio.Agent" -ErrorAction SilentlyContinue | Stop-Process -Force
Get-Process -Name "dotnet" -ErrorAction SilentlyContinue | Where-Object { $_.CommandLine -like "*Thrall.Radio.Agent*" } | Stop-Process -Force
Start-Sleep -Seconds 3

# 3. Extract and Overwrite
Log "Extracting binaries into active directory..."
Expand-Archive -Path $ZipPath -DestinationPath $InstallDirectory -Force

# 4. Clean up temp files
Remove-Item -Path $ZipPath -Force

# 5. Relaunch the Agent (Check if running as service or executable)
Log "Relaunching Agent..."
$ExePath = Join-Path $InstallDirectory "Thrall.Radio.Agent.exe"
if (Test-Path $ExePath) {
    Start-Process -FilePath $ExePath -WorkingDirectory $InstallDirectory -WindowStyle Hidden
    Log "Spawned independent Agent Executable."
} else {
    Log "No Executable found, attempting simple 'dotnet run' fallback."
    Start-Process -FilePath "dotnet" -ArgumentList "run" -WorkingDirectory $InstallDirectory -WindowStyle Hidden
}

Log "OTA Update Protocol Complete."
