# Register / remove IuVe Connect Desktop Agent as a Windows Scheduled Task (logon).
# Prefer Task Scheduler over HKCU Run for restart-on-failure and cleaner UAC behavior.
param(
    [Parameter(Mandatory = $true)]
    [ValidateSet("install", "uninstall", "status")]
    [string]$Action,

    [Parameter(Mandatory = $false)]
    [string]$InstallDir = "",

    [Parameter(Mandatory = $false)]
    [string]$Pythonw = "",

    [Parameter(Mandatory = $false)]
    [string]$ConfigPath = ""
)

Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"

$TaskName = "IuVeConnectDesktopAgent"
$TaskPath = "\"

function Resolve-Defaults {
    if ([string]::IsNullOrWhiteSpace($InstallDir)) {
        $InstallDir = Join-Path $env:LOCALAPPDATA "IuVeConnectAgent"
    }
    if ([string]::IsNullOrWhiteSpace($Pythonw)) {
        $candidate = Join-Path $InstallDir "runtime\python\pythonw.exe"
        if (Test-Path $candidate) { $script:Pythonw = $candidate }
        else { $script:Pythonw = (Join-Path $InstallDir "runtime\python\python.exe") }
    }
    if ([string]::IsNullOrWhiteSpace($ConfigPath)) {
        $script:ConfigPath = Join-Path $env:USERPROFILE ".config\iuve-connect-agent\desktop-config.json"
    }
    $script:InstallDir = $InstallDir
}

function Install-AgentTask {
    Resolve-Defaults
    if (-not (Test-Path $Pythonw)) {
        throw "pythonw_missing:$Pythonw"
    }
    $arg = "-m iuve_connect_agents.desktop.app run --config `"$ConfigPath`""
    $action = New-ScheduledTaskAction -Execute $Pythonw -Argument $arg -WorkingDirectory $InstallDir
    $trigger = New-ScheduledTaskTrigger -AtLogOn -User $env:USERNAME
    $settings = New-ScheduledTaskSettingsSet `
        -AllowStartIfOnBatteries `
        -DontStopIfGoingOnBatteries `
        -StartWhenAvailable `
        -RestartCount 3 `
        -RestartInterval (New-TimeSpan -Minutes 1) `
        -ExecutionTimeLimit (New-TimeSpan -Days 0)
    $principal = New-ScheduledTaskPrincipal -UserId $env:USERNAME -LogonType Interactive -RunLevel Limited
    Register-ScheduledTask `
        -TaskName $TaskName `
        -TaskPath $TaskPath `
        -Action $action `
        -Trigger $trigger `
        -Settings $settings `
        -Principal $principal `
        -Force | Out-Null

    # Drop legacy Run key once Task Scheduler is registered.
    $runKey = "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run"
    if (Get-ItemProperty -Path $runKey -Name "IuVeConnectDesktopAgent" -ErrorAction SilentlyContinue) {
        Remove-ItemProperty -Path $runKey -Name "IuVeConnectDesktopAgent" -ErrorAction SilentlyContinue
    }
    Write-Output "ok:task_installed:$TaskName"
}

function Uninstall-AgentTask {
    Unregister-ScheduledTask -TaskName $TaskName -Confirm:$false -ErrorAction SilentlyContinue
    $runKey = "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run"
    Remove-ItemProperty -Path $runKey -Name "IuVeConnectDesktopAgent" -ErrorAction SilentlyContinue
    Write-Output "ok:task_removed:$TaskName"
}

function Show-AgentTaskStatus {
    $task = Get-ScheduledTask -TaskName $TaskName -ErrorAction SilentlyContinue
    if ($null -eq $task) {
        Write-Output "missing"
        return
    }
    $info = Get-ScheduledTaskInfo -TaskName $TaskName -ErrorAction SilentlyContinue
    Write-Output ("state={0};lastResult={1}" -f $task.State, $(if ($info) { $info.LastTaskResult } else { "n/a" }))
}

switch ($Action) {
    "install" { Install-AgentTask }
    "uninstall" { Uninstall-AgentTask }
    "status" { Show-AgentTaskStatus }
}
