# Ensure running as Administrator
if (-not ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole(`
    [Security.Principal.WindowsBuiltInRole] "Administrator")) {
    Write-Error "Please run this script as Administrator."
    exit 1
}

Write-Output "Applying Windows gaming performance optimizations..."

# 1. Set High Performance Power Plan
Write-Output "Setting High Performance power plan..."
powercfg -setactive SCHEME_MIN

# 2. Disable Windows Defender real-time protection
Write-Output "Disabling Windows Defender Real-Time Protection..."
Set-MpPreference -DisableRealtimeMonitoring $true

# Run as Administrator

Write-Host "Disabling unnecessary startup applications..." -ForegroundColor Cyan

# --- 1. Disable from Registry (HKCU)
$startupRegHKCU = "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run"
$disableListHKCU = @(
    "OneDrive",
    "EpicGamesLauncher",
    "EADM",
    "Microsoft.Lists",
    "MicrosoftEdgeAutoLaunch_4F5320B4C77A9527F492603BB81F11D5"
)

foreach ($name in $disableListHKCU) {
    if (Get-ItemProperty -Path $startupRegHKCU -Name $name -ErrorAction SilentlyContinue) {
        Write-Host "Removing HKCU startup item: $name"
        Remove-ItemProperty -Path $startupRegHKCU -Name $name
    }
}

# --- 2. Disable from Registry (HKLM)
$startupRegHKLM = "HKLM:\Software\Microsoft\Windows\CurrentVersion\Run"
$disableListHKLM = @(
    "SecurityHealth"  # optional; comment this line to keep Windows Security Tray
)

foreach ($name in $disableListHKLM) {
    if (Get-ItemProperty -Path $startupRegHKLM -Name $name -ErrorAction SilentlyContinue) {
        Write-Host "Removing HKLM startup item: $name"
        Remove-ItemProperty -Path $startupRegHKLM -Name $name
    }
}

# --- 3. Disable startup folder entries
$startupFolders = @(
    "$env:APPDATA\Microsoft\Windows\Start Menu\Programs\Startup",
    "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup"
)

foreach ($folder in $startupFolders) {
    Get-ChildItem $folder -Filter *.lnk -ErrorAction SilentlyContinue | ForEach-Object {
        Write-Host "Disabling startup shortcut: $($_.Name)"
        Remove-Item $_.FullName -Force
    }
}

Write-Host "`n✅ Startup applications optimized. Reboot to apply changes." -ForegroundColor Green

# 4. Disable background services
Write-Output "Disabling unnecessary background services..."
$servicesToDisable = @(
    "DiagTrack",          # Connected User Experience and Telemetry
    "SysMain",            # Superfetch
    "WSearch",            # Windows Search
    "XblGameSave",        # Xbox services
    "MapsBroker",         # Maps background service
    "OneSyncSvc"          # OneDrive sync
    "AdobeARMservice",
    "ClickToRunSvc",
    "edgeupdate",
    "OneSyncSvc_78aa3",
    "CDPUserSvc_78aa3",
    "CDPSvc",
    "webthreatdefusersvc_78aa3",
    "WpnService",
    "WpnUserService_78aa3",
    "Spooler",
    "SCardSvr",
    "MicrosoftEdgeAutoLaunch_4F5320B4C77A9527F492603BB81F11D5",
    "vorpX Service"
)

foreach ($svc in $servicesToDisable) {
    try {
        Write-Host "Disabling service: $svc" -ForegroundColor Yellow
        Stop-Service -Name $svc -Force -ErrorAction SilentlyContinue
        Set-Service -Name $svc -StartupType Disabled
    } catch {
        Write-Host "Could not disable ${svc}: $_" -ForegroundColor Red    }
}

# 5. NVIDIA GPU Tweaks - Launch NVIDIA Control Panel (manual steps)
Write-Output "`n[!] Please open NVIDIA Control Panel and set:"
Write-Output "- Power Management: Prefer Maximum Performance"
Write-Output "- Low Latency Mode: Ultra"
Write-Output "- Vertical Sync: Off or Fast Sync (depending on monitor)"
Start-Process "nvcplui.exe"

# 6. Disable Xbox Game Bar and DVR
Write-Output "Disabling Xbox Game Bar and DVR..."
reg add "HKCU\Software\Microsoft\Windows\CurrentVersion\GameDVR" /v "AppCaptureEnabled" /t REG_DWORD /d 0 /f
reg add "HKCU\System\GameConfigStore" /v "GameDVR_Enabled" /t REG_DWORD /d 0 /f
reg add "HKCU\System\GameConfigStore" /v "GameDVR_FSEBehaviorMode" /t REG_DWORD /d 2 /f
reg add "HKCU\System\GameConfigStore" /v "GameDVR_HonorUserFSEBehaviorMode" /t REG_DWORD /d 1 /f

# 7. Disable Notifications
Write-Output "Disabling Windows notifications..."
reg add "HKCU\Software\Microsoft\Windows\CurrentVersion\PushNotifications" /v "ToastEnabled" /t REG_DWORD /d 0 /f

Write-Output "`n✅ Optimization complete. Please restart your VM for all changes to take effect."
