#Requires -Version 5.1
param (
    [Parameter(Mandatory=$true)]  [string]$BackendUrl,
    [Parameter(Mandatory=$true)]  [string]$Group,
    [Parameter(Mandatory=$true)]  [string]$UnitId,
    [string]$RdpNickname = "UnknownRDP",
    [int]   $VMId        = 0
)

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

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

function Write-Step { param([int]$N, [int]$Total, [string]$Msg)
    Write-Host "[$N/$Total] $Msg" -ForegroundColor Yellow
}
function Write-OK   { param([string]$Msg) Write-Host "      [OK] $Msg" -ForegroundColor Green }
function Write-Fail { param([string]$Msg) Write-Host "      [FAIL] $Msg" -ForegroundColor Red }

Write-Host ""
Write-Host "+======================================+" -ForegroundColor Cyan
Write-Host "|    SinnerWatchdog Agent Installer    |" -ForegroundColor Cyan
Write-Host "+======================================+" -ForegroundColor Cyan
Write-Host ""
Write-Host "  Backend : $BackendUrl" -ForegroundColor Gray
Write-Host "  Group   : $Group"      -ForegroundColor Gray
Write-Host "  Unit ID : $UnitId"     -ForegroundColor Gray
Write-Host "  RDP     : $RdpNickname" -ForegroundColor Gray
Write-Host ""

$err = $false

Write-Step 1 5 "Removing existing installation (if any)..."
try {
    $existing = Get-ScheduledTask -TaskName $TaskName -ErrorAction SilentlyContinue
    if ($existing) {
        Stop-ScheduledTask       -TaskName $TaskName -ErrorAction SilentlyContinue
        Unregister-ScheduledTask -TaskName $TaskName -Confirm:$false -ErrorAction SilentlyContinue
        Write-OK "Old task removed"
    } else {
        Write-OK "No existing task found"
    }
} catch { Write-OK "Skipped (no existing install)" }

Write-Step 2 5 "Creating agent directory..."
try {
    if (!(Test-Path $AgentDir)) { New-Item -ItemType Directory -Path $AgentDir -Force | Out-Null }
    Write-OK $AgentDir
} catch {
    Write-Fail "Cannot create directory: $_"
    $err = $true
}

if (-not $err) {
    Write-Step 3 5 "Downloading agent from server..."
    try {
        $wc = New-Object System.Net.WebClient
        $wc.Headers.Add("Cache-Control", "no-cache")
        $wc.DownloadFile("$BackendUrl/static/agent.ps1", $AgentPath)

        $content = Get-Content $AgentPath -Raw
        if ($content.Length -lt 500 -or $content -notmatch 'AGENT_VERSION') {
            throw "Downloaded file looks invalid or incomplete"
        }
        Write-OK "agent.ps1 downloaded and verified"
    } catch {
        Write-Fail "Download failed: $_"
        $err = $true
    }
}

if (-not $err) {
    Write-Step 4 5 "Creating scheduled task..."
    try {
        $argList = "-NoProfile -WindowStyle Hidden -ExecutionPolicy Bypass -File `"$AgentPath`"" +
                   " -BackendUrl `"$BackendUrl`"" +
                   " -Group `"$Group`"" +
                   " -UnitId `"$UnitId`"" +
                   " -RdpNickname `"$RdpNickname`""
        if ($VMId -gt 0) { $argList += " -VMId $VMId" }

        $action   = New-ScheduledTaskAction  -Execute "powershell.exe" -Argument $argList
        $trigger  = New-ScheduledTaskTrigger -AtLogon
        $settings = New-ScheduledTaskSettingsSet `
            -AllowStartIfOnBatteries `
            -DontStopIfGoingOnBatteries `
            -StartWhenAvailable `
            -Hidden `
            -RestartCount 5 `
            -RestartInterval (New-TimeSpan -Minutes 2)

        Register-ScheduledTask -Action $action -Trigger $trigger -Settings $settings `
            -TaskName $TaskName -RunLevel Highest -Force | Out-Null

        Write-OK "Task '$TaskName' registered (runs at logon, restarts on failure)"
    } catch {
        Write-Fail "Task registration failed: $_"
        $err = $true
    }
}

if (-not $err) {
    Write-Step 5 5 "Starting agent..."
    try {
        Start-ScheduledTask -TaskName $TaskName
        Start-Sleep 2
        $state = (Get-ScheduledTask -TaskName $TaskName).State
        Write-OK "Agent started (state: $state)"
    } catch {
        Write-Fail "Could not start agent: $_"
        $err = $true
    }
}

Write-Host ""
Write-Host "+======================================+" -ForegroundColor Cyan
if ($err) {
    Write-Host "|         INSTALLATION FAILED          |" -ForegroundColor Red
    Write-Host "+======================================+" -ForegroundColor Cyan
    Write-Host ""
    exit 1
} else {
    Write-Host "|       INSTALLATION SUCCESSFUL        |" -ForegroundColor Green
    Write-Host "+======================================+" -ForegroundColor Cyan
    Write-Host ""
    Write-Host "  Agent is running. It will auto-update" -ForegroundColor Gray
    Write-Host "  every 30 minutes from the server."     -ForegroundColor Gray
    Write-Host "  No reinstall needed for future updates." -ForegroundColor Gray
    Write-Host ""
    $logPath = "$AgentDir\agent.log"
    Write-Host "  Log: $logPath" -ForegroundColor DarkGray
    Write-Host ""
}