#Requires -RunAsAdministrator
$ErrorActionPreference = "Stop"
. (Join-Path $PSScriptRoot "_env.ps1")

if (-not $DesktopApp -or -not (Test-Path (Join-Path $DesktopApp "net_monitor.py"))) {
  Write-Host "net_monitor.py not found - skip monitor task" -ForegroundColor Yellow
  return
}

# The bundled interpreter first, then whatever Find-CpcPython turns up. This list
# used to start with the developer's own "E:\Python\pythonw.exe" - harmless here,
# but the monitor silently ran on a foreign interpreter on any machine that had one.
$py = Find-CpcBundledPython -Windowed
if (-not $py) {
  $console = Find-CpcPython
  if ($console) {
    # pythonw keeps the five-minute task from flashing a console window
    $w = Join-Path (Split-Path $console -Parent) "pythonw.exe"
    $py = $(if (Test-Path $w) { $w } else { $console })
  }
}
if (-not $py) {
  # Not fatal: the monitor is a nicety, the product installs and runs without it.
  Write-Host "  WARN: no Python found - skipping the net monitor task" -ForegroundColor Yellow
  return
}

$script = Join-Path $DesktopApp "net_monitor.py"
$wrap = Join-Path $ProductHome "run_net_monitor_hidden.vbs"
@(
  'Set sh = CreateObject("Wscript.Shell")'
  ('sh.Run """' + $py + '"" ""' + $script + '""", 0, False')
) | Set-Content -Path $wrap -Encoding ASCII

Unregister-ScheduledTask -TaskName $TaskMonitor -Confirm:$false -ErrorAction SilentlyContinue
$wscript = Join-Path $env:SystemRoot "System32\wscript.exe"
$action = New-ScheduledTaskAction -Execute $wscript -Argument "//nologo `"$wrap`""
$trigger = New-ScheduledTaskTrigger -Once -At ((Get-Date).AddMinutes(1)) -RepetitionInterval (New-TimeSpan -Minutes 5) -RepetitionDuration (New-TimeSpan -Days 3650)
$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -StartWhenAvailable -MultipleInstances IgnoreNew -Hidden
# См. Install-SotaCaptureWatcher.ps1: под UAC $env:USERNAME — это учётка, которую
# подтвердили в окне, а не владелец компьютера.
$targetUser = $env:CPC_TARGET_USER
if (-not $targetUser) { $targetUser = $env:USERNAME }
$principal = New-ScheduledTaskPrincipal -UserId $targetUser -LogonType Interactive
Register-ScheduledTask -TaskName $TaskMonitor -Action $action -Trigger $trigger -Settings $settings -Principal $principal -Force | Out-Null
Write-Host ("Installed: " + $TaskMonitor) -ForegroundColor Green
