param(
    [string]$TaskName = "RalphInboxDaemon",
    [int]$PollSeconds = 15,
    [string]$Implementer = "",
    [string[]]$Reviewers = @(),
    [switch]$DisableCodexMaster,
    [switch]$DisableAutoFix,
    [switch]$DryRun,
    [switch]$AtStartup,
    [switch]$AtLogon = $true
)

. (Join-Path $PSScriptRoot "Common.ps1")

$daemonScript = Join-Path $PSScriptRoot "Start-RalphInboxDaemon.ps1"
$argParts = @(
    "-NoProfile",
    "-WindowStyle Hidden",
    "-ExecutionPolicy Bypass",
    ('-File "{0}"' -f $daemonScript),
    ('-PollSeconds {0}' -f $PollSeconds)
)

if (-not [string]::IsNullOrWhiteSpace($Implementer)) {
    $argParts += ('-Implementer "{0}"' -f $Implementer)
}
foreach ($reviewer in $Reviewers) {
    $argParts += ('-Reviewers "{0}"' -f $reviewer)
}
if ($DisableCodexMaster) {
    $argParts += "-DisableCodexMaster"
}
if ($DisableAutoFix) {
    $argParts += "-DisableAutoFix"
}
if ($DryRun) {
    $argParts += "-DryRun"
}

$action = New-ScheduledTaskAction -Execute "powershell.exe" -Argument ($argParts -join " ")
$triggers = @()
if ($AtStartup) {
    $triggers += New-ScheduledTaskTrigger -AtStartup
}
if ($AtLogon) {
    $triggers += New-ScheduledTaskTrigger -AtLogOn
}
if ($triggers.Count -eq 0) {
    throw "At least one trigger must be enabled."
}

$settings = New-ScheduledTaskSettingsSet -MultipleInstances IgnoreNew -StartWhenAvailable -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries
$principal = New-ScheduledTaskPrincipal -UserId $env:USERNAME -LogonType Interactive -RunLevel Highest

Register-ScheduledTask -TaskName $TaskName -Action $action -Trigger $triggers -Settings $settings -Principal $principal -Force | Out-Null

(@{
    task_name = $TaskName
    installed = $true
    poll_seconds = $PollSeconds
    dry_run = [bool]$DryRun
} | ConvertTo-Json -Depth 20)
