[CmdletBinding()]
param(
    [string]$TaskName = "TradeBot PyTorch Forecaster Retrainer",
    [int]$EveryHours = 6,
    [string]$Symbols = "",
    [int]$Limit = 3000,
    [int]$Horizon = 0,
    [string]$Horizons = "",
    [string]$Features = "",
    [string]$ContextSymbols = "",
    [int]$FirstRunMinutes = 0,
    [switch]$DeployToPi,
    [string]$PiHost = "192.168.0.185",
    [string]$PiUser = "sevenhill",
    [string]$PiRoot = "/mnt/data/tradebot",
    [string]$PiSshKeyPath = ""
)

$ErrorActionPreference = "Stop"

$RepoRoot = (Resolve-Path (Join-Path $PSScriptRoot "..")).Path
$Runner = Join-Path $RepoRoot "tools\run_torch_retrain.ps1"
if (-not (Test-Path $Runner)) {
    throw "Runner not found: $Runner"
}

$LegacyTaskName = "TradeBot LSTM Retrainer"
if ($TaskName -ne $LegacyTaskName) {
    $legacyTask = Get-ScheduledTask -TaskName $LegacyTaskName -ErrorAction SilentlyContinue
    if ($legacyTask) {
        Unregister-ScheduledTask -TaskName $LegacyTaskName -Confirm:$false
    }
}

$actionArgs = "-NoProfile -ExecutionPolicy Bypass -File `"$Runner`""
if ($Symbols) {
    $actionArgs += " -Symbols `"$Symbols`""
}
if ($Limit -gt 0) {
    $actionArgs += " -Limit $Limit"
}
if ($Horizon -gt 0) {
    $actionArgs += " -Horizon $Horizon"
}
if ($Horizons) {
    $actionArgs += " -Horizons `"$Horizons`""
}
if ($Features) {
    $actionArgs += " -Features `"$Features`""
}
if ($ContextSymbols) {
    $actionArgs += " -ContextSymbols `"$ContextSymbols`""
}
if ($DeployToPi) {
    $actionArgs += " -DeployToPi"
}
if ($PiHost) {
    $actionArgs += " -PiHost `"$PiHost`""
}
if ($PiUser) {
    $actionArgs += " -PiUser `"$PiUser`""
}
if ($PiRoot) {
    $actionArgs += " -PiRoot `"$PiRoot`""
}
if ($PiSshKeyPath) {
    $actionArgs += " -PiSshKeyPath `"$PiSshKeyPath`""
}
$action = New-ScheduledTaskAction -Execute "powershell.exe" -Argument $actionArgs -WorkingDirectory $RepoRoot
$trigger = New-ScheduledTaskTrigger `
    -Once `
    -At (Get-Date).AddMinutes($(if ($FirstRunMinutes -gt 0) { $FirstRunMinutes } else { $EveryHours * 60 })) `
    -RepetitionInterval (New-TimeSpan -Hours $EveryHours) `
    -RepetitionDuration (New-TimeSpan -Days 3650)
$principal = New-ScheduledTaskPrincipal `
    -UserId ([System.Security.Principal.WindowsIdentity]::GetCurrent().Name) `
    -LogonType Interactive `
    -RunLevel Limited
$settings = New-ScheduledTaskSettingsSet `
    -StartWhenAvailable `
    -MultipleInstances IgnoreNew `
    -AllowStartIfOnBatteries `
    -DontStopIfGoingOnBatteries

Register-ScheduledTask `
    -TaskName $TaskName `
    -Action $action `
    -Trigger $trigger `
    -Principal $principal `
    -Settings $settings `
    -Description "Retrains TradeBot PyTorch recurrent forecast parameters every $EveryHours hours." `
    -Force | Out-Null

Write-Host "Registered scheduled task '$TaskName' every $EveryHours hours."
