param (
    [Parameter(Mandatory=$true)]
    [string]$NewPassword,

    [Parameter(Mandatory=$true)]
    [string]$SteamCmdPath,
    
    [Parameter(Mandatory=$true)]
    [string]$SteamUser,

    [Parameter(Mandatory=$true)]
    [string]$SteamPassword,

    [string[]]$GameIds
)

$ErrorActionPreference = "Stop"

# Ensure correct display of Czech characters in the console (handles "Handle is invalid" error)
try {
    # Attempt to set the console and PowerShell encoding
    $OutputEncoding = [System.Console]::OutputEncoding = [System.Text.Encoding]::UTF8
} catch {
    # If running in a non-interactive mode (without a window), setting console encoding may fail.
    # In this case, at least set the internal PowerShell variable and continue.
    $OutputEncoding = [System.Text.Encoding]::UTF8
}

# Define the current script's path for reliable sub-script calls
Set-Location $PSScriptRoot

# 1. Check for Administrator privileges
if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
    Write-Error "Script must be run as Administrator."
    exit 5
}

Write-Host "Setting VNC password and starting service..." -ForegroundColor Green
& "./ChangeTVNPassword.ps1" -NewPassword $NewPassword

Write-Host "Setting Gamer user password..." -ForegroundColor Green
& "./ChangeGamerPassword.ps1" -newPassword $NewPassword

# --- Process GameIds (if provided) ---
if ($GameIds.Count -gt 0) {
    Write-Host "Processing Game IDs: $($GameIds -join ', ')" -ForegroundColor Magenta
    
    # Prepare parameters for cleaner invocation (Splatting)
    $InstallParams = @{
        SteamCmdPath = $SteamCmdPath
        SteamUser    = $SteamUser
        Password     = $SteamPassword
        GameIds      = $GameIds
    }

    # Invoke the sub-script with parameters spread across multiple lines (using @InstallParams)
    & "./InstallSteamGames.ps1" @InstallParams
}
# -------------------------------------


# 2. Enable UWF
Write-Host "Enabling UWF filter..." -ForegroundColor Green
uwfmgr.exe filter enable | Out-Null

# 3. Restart in 3 seconds
Write-Host "Scheduling restart in 3 seconds..." -ForegroundColor Cyan
# It's better to use direct shutdown /f here to ensure hanging processes don't block the restart
shutdown.exe /r /t 3 /f

# 4. Exit code 0
Write-Host "Returning exit_code 0"
exit 0
