# PULSE Windows Service Installer
# Creates a Scheduled Task that runs `pulse start` at user logon,
# ensuring the OS survives reboots without manual intervention.
#
# Usage (run as Administrator):
#   powershell -ExecutionPolicy Bypass -File scripts\install_pulse_service.ps1
#
# To uninstall:
#   powershell -ExecutionPolicy Bypass -File scripts\install_pulse_service.ps1 -Uninstall

param(
    [switch]$Uninstall
)

$TaskName = "PULSE-Orchestrator"
$Description = "PULSE Neural OS — auto-starts orchestrator + worker supervisor at logon"

if ($Uninstall) {
    Write-Host "[PULSE] Removing scheduled task '$TaskName'..."
    Unregister-ScheduledTask -TaskName $TaskName -Confirm:$false -ErrorAction SilentlyContinue
    Write-Host "[PULSE] Done. PULSE will no longer auto-start at logon."
    exit 0
}

# Find Python
$Python = (Get-Command python -ErrorAction SilentlyContinue).Source
if (-not $Python) {
    $Python = (Get-Command python3 -ErrorAction SilentlyContinue).Source
}
if (-not $Python) {
    Write-Host "[PULSE] ERROR: Python not found in PATH. Install Python first."
    exit 1
}

# Find PULSE root (this script lives in scripts/)
$ScriptRoot = Split-Path -Parent $MyInvocation.MyCommand.Path
$PulseRoot = Split-Path -Parent $ScriptRoot

# Verify pulse package exists
if (-not (Test-Path "$PulseRoot\pulse\cli\main.py")) {
    Write-Host "[PULSE] ERROR: pulse package not found at $PulseRoot"
    exit 1
}

Write-Host "[PULSE] Python: $Python"
Write-Host "[PULSE] PULSE root: $PulseRoot"

# Build the action: python -m pulse start
$Action = New-ScheduledTaskAction `
    -Execute $Python `
    -Argument "-m pulse start" `
    -WorkingDirectory $PulseRoot

# Trigger: at user logon (with 30s delay for network)
$Trigger = New-ScheduledTaskTrigger -AtLogOn
$Trigger.Delay = "PT30S"

# Settings: restart on failure, don't stop on idle
$Settings = New-ScheduledTaskSettingsSet `
    -AllowStartIfOnBatteries `
    -DontStopIfGoingOnBatteries `
    -RestartCount 3 `
    -RestartInterval (New-TimeSpan -Minutes 1) `
    -StartWhenAvailable `
    -ExecutionTimeLimit (New-TimeSpan -Days 365)

# Register
Register-ScheduledTask `
    -TaskName $TaskName `
    -Description $Description `
    -Action $Action `
    -Trigger $Trigger `
    -Settings $Settings `
    -RunLevel Highest `
    -Force

Write-Host ""
Write-Host "[PULSE] Scheduled task '$TaskName' installed successfully."
Write-Host "[PULSE] The orchestrator will auto-start at every logon."
Write-Host "[PULSE] To remove: powershell -File scripts\install_pulse_service.ps1 -Uninstall"
