Unregister-ScheduledTask -TaskName "MediaServer" -Confirm:$false -ErrorAction SilentlyContinue

# Get the media-server directory (parent of scripts folder)
$serverRoot = (Get-Item $PSScriptRoot).Parent.FullName
$vbsPath = Join-Path $PSScriptRoot "start-hidden.vbs"

if (-not (Test-Path $vbsPath)) {
    Write-Error "start-hidden.vbs not found in scripts folder."
    exit 1
}

# Launch via wscript + VBS to run python completely hidden (no console window)
$action = New-ScheduledTaskAction -Execute "wscript.exe" -Argument "`"$vbsPath`"" -WorkingDirectory $serverRoot
$trigger = New-ScheduledTaskTrigger -AtLogon -User "$env:USERNAME"
$principal = New-ScheduledTaskPrincipal -UserId "$env:USERNAME" -LogonType Interactive -RunLevel Highest
$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -StartWhenAvailable
Register-ScheduledTask -TaskName "MediaServer" -Action $action -Trigger $trigger -Principal $principal -Settings $settings -Description "Media Server for Home Assistant"

Write-Host "Scheduled task 'MediaServer' created with working directory: $serverRoot"
