# Creates a Windows Scheduled Task to run license heartbeat every 5 minutes.
# Run as Administrator once per on-prem server.

$ErrorActionPreference = "Stop"
$Root = Split-Path -Parent $PSScriptRoot
$Script = Join-Path $Root "deploy\local_license_heartbeat.ps1"
$TaskName = "CNPERP-LicenseHeartbeat"

if (-not (Test-Path $Script)) {
    Write-Error "Script not found: $Script"
}

$Action = New-ScheduledTaskAction -Execute "powershell.exe" `
    -Argument "-NoProfile -ExecutionPolicy Bypass -File `"$Script`"" `
    -WorkingDirectory $Root

$Trigger = New-ScheduledTaskTrigger -Once -At (Get-Date).AddMinutes(1) `
    -RepetitionInterval (New-TimeSpan -Minutes 5) `
    -RepetitionDuration ([TimeSpan]::MaxValue)

$Settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries `
    -StartWhenAvailable -RunOnlyIfNetworkAvailable

Register-ScheduledTask -TaskName $TaskName -Action $Action -Trigger $Trigger `
    -Settings $Settings -Description "CNPERP license heartbeat to CNP cloud hub" -Force

Write-Host "Scheduled task '$TaskName' created (every 5 minutes)." -ForegroundColor Green
Write-Host "Ensure deploy\license-node.json exists and is configured."
