param (
    [string]$BackendUrl,
    [int]$VMId = 0,
    [string]$Group,
    [string]$UnitId,
    [string]$RdpNickname = "UnknownRDP"
)

Write-Host "`n========================================" -ForegroundColor Cyan
Write-Host "  SinnerWatchdog Agent Installer" -ForegroundColor Cyan
Write-Host "========================================`n" -ForegroundColor Cyan

$AgentDir = "$env:APPDATA\SinnerWatchdog"
$AgentPath = "$AgentDir\agent.ps1"
$TaskName = "SinnerWatchdogAgent"
$ErrorOccurred = $false

try {
    $task = Get-ScheduledTask -TaskName $TaskName -ErrorAction SilentlyContinue
    if ($task) {
        Stop-ScheduledTask -TaskName $TaskName -ErrorAction SilentlyContinue
        Unregister-ScheduledTask -TaskName $TaskName -Confirm:$false -ErrorAction SilentlyContinue
        $args = $task.Actions[0].Arguments
        if ($args -match '-File\s+"([^"]+)"') {
            $oldDir = Split-Path $matches[1] -Parent
            if ($oldDir -and (Test-Path $oldDir)) {
                Remove-Item $oldDir -Recurse -Force -ErrorAction SilentlyContinue
            }
        }
    }
} catch {}

Write-Host "[1/4] Creating agent directory..." -ForegroundColor Yellow
try {
    if (-not (Test-Path $AgentDir)) {
        New-Item -ItemType Directory -Path $AgentDir | Out-Null
    }
    Write-Host "      Directory ready" -ForegroundColor Green
} catch {
    $ErrorOccurred = $true
}

Write-Host "`n[2/4] Downloading agent script..." -ForegroundColor Yellow
try {
    Invoke-WebRequest -Uri "$BackendUrl/static/agent.ps1" -OutFile $AgentPath -ErrorAction Stop
    Write-Host "      Agent downloaded successfully" -ForegroundColor Green
} catch {
    $ErrorOccurred = $true
}

if (-not $ErrorOccurred) {
    Write-Host "`n[3/4] Setting up scheduled task..." -ForegroundColor Yellow
    try {
        if ($VMId -gt 0) {
            $AgentArgs = "-NoProfile -WindowStyle Hidden -ExecutionPolicy Bypass -File `"$AgentPath`" -BackendUrl `"$BackendUrl`" -VMId $VMId -UnitId `"$UnitId`" -Group `"$Group`" -RdpNickname `"$RdpNickname`""
        } else {
            $AgentArgs = "-NoProfile -WindowStyle Hidden -ExecutionPolicy Bypass -File `"$AgentPath`" -BackendUrl `"$BackendUrl`" -Group `"$Group`" -UnitId `"$UnitId`" -RdpNickname `"$RdpNickname`""
        }

        $Action = New-ScheduledTaskAction -Execute "powershell.exe" -Argument $AgentArgs
        $Trigger = New-ScheduledTaskTrigger -AtLogon
        $Settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -StartWhenAvailable -Hidden

        Register-ScheduledTask -Action $Action -Trigger $Trigger -Settings $Settings -TaskName $TaskName -Force | Out-Null
        Write-Host "      Scheduled task created" -ForegroundColor Green
    } catch {
        $ErrorOccurred = $true
    }
}

if (-not $ErrorOccurred) {
    Write-Host "`n[4/4] Starting agent..." -ForegroundColor Yellow
    try {
        Start-ScheduledTask -TaskName $TaskName
        Write-Host "      Agent started successfully" -ForegroundColor Green
    } catch {
        $ErrorOccurred = $true
    }
}

Write-Host "`n========================================" -ForegroundColor Cyan
if ($ErrorOccurred) {
    Write-Host "  INSTALLATION FAILED" -ForegroundColor Red
    Write-Host "========================================`n" -ForegroundColor Cyan
    exit 1
} else {
    Write-Host "  INSTALLATION SUCCESSFUL" -ForegroundColor Green
    Write-Host "========================================`n" -ForegroundColor Cyan
    exit 0
}
