param(
    [switch]$TestScan,
    [switch]$SelfTest,
    [switch]$UiSmokeTest,
    [switch]$SmartGlobalDiagnostics,
    [switch]$LicenseSmokeTest,
    [string]$LicenseKey = '',
    [string]$LicenseServerUrl = 'http://127.0.0.1:3000',
    [string]$DeviceId = '',
    [ValidateSet('','Scan','Normal','Extreme','Restore','LicenseStatus','Telemetry','Launch','LaunchPath','Preflight','NetworkProbe','RunningGames','GetProfile','SetProfile','ApplyTuning','UpdateCheck')]
    [string]$WinUiAction = '',
    [string]$WinUiGameName = '',
    [string]$WinUiGamePath = '',
    [ValidateSet('Normal','Extreme')]
    [string]$WinUiLaunchMode = 'Normal',
    [ValidateSet('Auto','Normal','Extreme','Competitive')]
    [string]$WinUiProfileMode = 'Auto',
    [ValidateSet('Balanced','High Performance','Competitive Low Latency','Quiet Saving')]
    [string]$WinUiTuningPreset = 'Balanced'
)

Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
Add-Type -AssemblyName System.Windows.Forms.DataVisualization

Add-Type -TypeDefinition @'
using System.Drawing;
using System.Windows.Forms;
namespace GameBoostUi {
    public class GlassPanel : Panel {
        public Color GlassColor { get; set; }
        public Color BorderColor { get; set; }
        public GlassPanel() {
            GlassColor = Color.FromArgb(176, 10, 18, 24);
            BorderColor = Color.FromArgb(115, 210, 230, 235);
            SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.ResizeRedraw | ControlStyles.SupportsTransparentBackColor, true);
            BackColor = Color.Transparent;
        }
        protected override void OnPaintBackground(PaintEventArgs e) {
            using (var brush = new SolidBrush(GlassColor)) e.Graphics.FillRectangle(brush, ClientRectangle);
        }
        protected override void OnPaint(PaintEventArgs e) {
            base.OnPaint(e);
            using (var pen = new Pen(BorderColor)) e.Graphics.DrawRectangle(pen, 0, 0, Width - 1, Height - 1);
        }
    }
}
'@ -ReferencedAssemblies 'System.Drawing','System.Windows.Forms' -ErrorAction Stop

[System.Windows.Forms.Application]::SetCompatibleTextRenderingDefault($false)
[System.Windows.Forms.Application]::EnableVisualStyles()
Add-Type -TypeDefinition @'
using System.Runtime.InteropServices;
public static class GameBoostTimerResolution {
    [DllImport("winmm.dll", EntryPoint="timeBeginPeriod")]
    public static extern uint TimeBeginPeriod(uint uMilliseconds);
    [DllImport("winmm.dll", EntryPoint="timeEndPeriod")]
    public static extern uint TimeEndPeriod(uint uMilliseconds);
}
'@ -ErrorAction SilentlyContinue

$script:PowerSchemeName = 'GameBoost Adaptive FPS'
$script:ExtremePowerSchemeName = 'GameBoost Extreme FPS'
$script:CustomTuningSchemeName = 'GameBoost Custom Tuning'
$script:OptimizedScheme = $null
$script:ExtremeScheme = $null
$script:FallbackScheme = $null
$script:PowerSchemeReady = $false
$script:PowerSchemeMessage = 'Power profile not initialized.'
$script:SystemProfile = $null
$script:AdaptivePlan = $null
$script:ExtremePlan = $null
$script:ExtremeModeActive = $false
$script:ExtremeSystemPolicyState = 'not_requested'
$script:TimerResolutionActive = $false
$script:SmartGlobalEnabled = $false
$script:SmartGlobalActiveGame = $null
$script:SmartGlobalActiveMode = ''
$script:SmartGlobalNoGameSince = $null
$script:SmartGlobalNextCheck = [DateTime]::MinValue
$script:SmartGlobalLastStatus = ''
$script:SmartGlobalCheckSeconds = 6
$script:SmartGlobalRestoreGraceSeconds = 45
$script:ThermalGuardEnabled = $true
$script:ThermalLimitC = 86
$script:ThermalResumeC = 80
$script:ThermalThrottleUntil = [DateTime]::MinValue
$script:MetricsLoggingEnabled = $false
$script:MetricsFolder = $null
$script:MetricsFile = $null
$script:MetricsAutoSession = $false
$script:MetricsSessionGame = ''
$script:MetricsSamples = New-Object System.Collections.ArrayList
$script:MetricsChartForm = $null
$script:MetricsChart = $null
$script:LatencyPing = $null
$script:LatencyTask = $null
$script:LastPingMs = $null
$script:LatencyTarget = '1.1.1.1'
$script:LearningFile = $null
$script:TuningFile = $null
$script:LastNetworkSummary = ''
$script:NetworkJob = $null
$script:LastAdviceSummary = ''
$script:SelectedGame = $null
$script:LastLaunch = $null
$script:Games = New-Object System.Collections.ArrayList
$script:CloseProcesses = @('SodaMusic', 'biubiu', 'doubao', 'Quark', 'QuarkUpdater')
$script:ExtremeCloseProcesses = @('SodaMusic', 'biubiu', 'doubao', 'Quark', 'QuarkUpdater', 'OneDrive', 'Teams', 'ms-teams', 'Discord', 'Spotify', 'QQMusic', 'cloudmusic', 'NeteaseMusic', 'BaiduNetdisk', 'WPSCloudSrv', 'PhoneExperienceHost', 'Widgets', 'WidgetService', 'XboxGameBarWidgets', 'GameBarPresenceWriter')
if ($PSCommandPath) {
    $script:AppRoot = Split-Path -Parent $PSCommandPath
} elseif ($PSScriptRoot) {
    $script:AppRoot = $PSScriptRoot
} else {
    $script:AppRoot = (Get-Location).Path
}
$script:LanguageFile = Join-Path $script:AppRoot 'app-language.json'
$script:MetricsFolder = Join-Path $script:AppRoot 'GameBoost-Metrics'
$script:LearningFile = Join-Path $script:AppRoot 'game-profiles.json'
$script:TuningFile = Join-Path $script:AppRoot 'custom-tuning-profiles.json'
$script:LicenseFile = Join-Path $script:AppRoot 'license-client.json'
$script:WinUiRestoreFile = Join-Path $script:AppRoot 'winui-restore-scheme.json'
$script:LicenseKey = $LicenseKey
$script:LicenseServerUrl = $LicenseServerUrl.TrimEnd('/')
$script:LicenseServerUrlWasSpecified = $PSBoundParameters.ContainsKey('LicenseServerUrl')
$script:AppVersion = '1.1.0'
$script:UpdateChecked = $false
$script:DeviceIdOverride = $DeviceId
$script:LicenseState = $null
$script:BackgroundImagePath = Join-Path $script:AppRoot 'Assets\GameBoostBackground.jpg'
$script:Language = 'zh-CN'
$script:Text = @{
    'zh-CN' = @{
        WindowTitle='GameBoost - 稳定帧率助手'; Subtitle='自适应 FPS 配置  |  Steam 自动扫描  |  本机硬件方案'; Language='中文 / EN'
        Games='已安装游戏'; Game='游戏'; Source='来源'; Status='状态'; Rescan='重新扫描'; AddExe='添加 EXE'; OptimizeAll='普通优化'; OptimizeExtreme='最佳优化'; SmartGlobal='智能全局'; Metrics='性能记录'; Chart='曲线'; Network='网络优化'; Thermal='温控保护'; Advice='画像建议'; Profile='保存画像'; Tuning='电脑调校'
        CurrentStatus='当前状态'; Ready='准备就绪'; ReadyDetail='请选择一个游戏，然后启动。'; SelectedNone='已选择：无'; Launch='优化并启动'; Restore='恢复普通配置'
        Active='已启用'; ScanComplete='扫描完成'; ExtremeActive='最佳优化已启用'; ExtremeState='极限'; ActiveState='已启用'; SmartGlobalOn='智能全局已开启'; SmartGlobalWaiting='智能全局待命'; SmartGlobalRestored='智能全局已恢复'; MetricsOn='性能记录中'; MetricsOff='性能记录已停止'; NetworkDone='网络优化完成'; ThermalDownshift='温控保护已降档'; AdviceReady='画像建议'; ProfileSaved='游戏画像已保存'
        SelectGame='请选择游戏'; SelectGameDetail='请先从列表中选择一个游戏。'; OptimizationActive='优化已启用'; AllFpsActive='全部 FPS 模式已启用'; NormalProfile='普通配置'; NormalProfileDetail='已恢复启动前的 Windows 电源计划。'
        OpenExeTitle='选择游戏可执行文件'; ExeFilter='游戏可执行文件 (*.exe)|*.exe'; PcProfile='电脑配置'; Power='电源计划'; State='状态'; Standby='待命'
    }
    'en-US' = @{
        WindowTitle='GameBoost - Stable FPS Assistant'; Subtitle='Adaptive FPS profile  |  Steam auto-scan  |  Local hardware plan'; Language='中文 / EN'
        Games='INSTALLED GAMES'; Game='Game'; Source='Source'; Status='Status'; Rescan='RESCAN'; AddExe='ADD EXE'; OptimizeAll='NORMAL'; OptimizeExtreme='EXTREME'; SmartGlobal='AUTO'; Metrics='LOG'; Chart='CHARTS'; Network='NET OPT'; Thermal='THERMAL'; Advice='ADVICE'; Profile='SAVE PROFILE'; Tuning='PC TUNE'
        CurrentStatus='CURRENT STATUS'; Ready='READY'; ReadyDetail='Select a game, then launch it.'; SelectedNone='Selected: none'; Launch='OPTIMIZE + LAUNCH'; Restore='RESTORE NORMAL PROFILE'
        Active='ACTIVE'; ScanComplete='SCAN COMPLETE'; ExtremeActive='EXTREME FPS ACTIVE'; ExtremeState='EXTREME'; ActiveState='ACTIVE'; SmartGlobalOn='AUTO GLOBAL ON'; SmartGlobalWaiting='AUTO GLOBAL STANDBY'; SmartGlobalRestored='AUTO GLOBAL RESTORED'; MetricsOn='PERFORMANCE LOGGING'; MetricsOff='PERFORMANCE LOG STOPPED'; NetworkDone='NETWORK OPTIMIZED'; ThermalDownshift='THERMAL GUARD DOWNSHIFT'; AdviceReady='GAME PROFILE ADVICE'; ProfileSaved='GAME PROFILE SAVED'
        SelectGame='SELECT A GAME'; SelectGameDetail='Choose a game from the list first.'; OptimizationActive='OPTIMIZATION ACTIVE'; AllFpsActive='ALL FPS MODE ACTIVE'; NormalProfile='NORMAL PROFILE'; NormalProfileDetail='The startup Windows power profile is active again.'
        OpenExeTitle='Select the game executable'; ExeFilter='Game executable (*.exe)|*.exe'; PcProfile='PC profile'; Power='Power'; State='State'; Standby='STANDBY'
    }
}

function Load-AppLanguage {
    if (Test-Path $script:LanguageFile) {
        try {
            $saved = (Get-Content -LiteralPath $script:LanguageFile -Raw -Encoding UTF8 | ConvertFrom-Json).Language
            if ($saved -in @('zh-CN','en-US')) { $script:Language = $saved }
        } catch {}
    }
}

function Save-AppLanguage {
    [ordered]@{ Language = $script:Language } | ConvertTo-Json | Set-Content -LiteralPath $script:LanguageFile -Encoding UTF8
}

function T { param([string]$Key) return $script:Text[$script:Language][$Key] }
Load-AppLanguage

function Get-GameBoostFeatureSet {
    param([string]$Plan)
    $proEnabled = $Plan -in @('pro','trial')
    return [pscustomobject][ordered]@{
        normalOptimization = $true
        launchGame = $true
        steamScan = $true
        extremeOptimization = $proEnabled
        smartGlobal = $proEnabled
        metricsLogging = $proEnabled
        networkOptimization = $proEnabled
        thermalGuard = $proEnabled
        gameProfiles = $proEnabled
        customTuning = $proEnabled
    }
}

function Get-GameBoostDeviceId {
    if ($script:DeviceIdOverride) { return $script:DeviceIdOverride }
    try {
        $machineGuid = (Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Cryptography' -Name MachineGuid -ErrorAction Stop).MachineGuid
        if ($machineGuid) { return $machineGuid }
    } catch {}
    return ($env:COMPUTERNAME + '-' + [Environment]::UserName)
}

function Read-GameBoostLicenseConfig {
    if (Test-Path -LiteralPath $script:LicenseFile) {
        try {
            $config = Get-Content -LiteralPath $script:LicenseFile -Raw -Encoding UTF8 | ConvertFrom-Json
            if (-not $script:LicenseKey -and $config.LicenseKey) { $script:LicenseKey = [string]$config.LicenseKey }
            if (-not $script:LicenseServerUrlWasSpecified -and $config.ServerUrl) { $script:LicenseServerUrl = ([string]$config.ServerUrl).TrimEnd('/') }
        } catch {}
    }
}

function Save-GameBoostLicenseConfig {
    if (-not $script:LicenseKey) { return }
    [ordered]@{
        LicenseKey = $script:LicenseKey
        ServerUrl = $script:LicenseServerUrl
        SavedAt = (Get-Date).ToString('s')
    } | ConvertTo-Json | Set-Content -LiteralPath $script:LicenseFile -Encoding UTF8
}

function Get-GameBoostUpdateManifestUri {
    return ($script:LicenseServerUrl.TrimEnd('/') + '/downloads/release.json')
}

function Test-GameBoostUpdate {
    try {
        $rawManifest = (Invoke-WebRequest -Method Get -Uri (Get-GameBoostUpdateManifestUri) -TimeoutSec 5).Content.TrimStart([char]0xFEFF)
        $manifest = $rawManifest | ConvertFrom-Json
        if (-not $manifest.version -or -not $manifest.downloadUrl) { return $null }
        $available = [version]([string]$manifest.version)
        $current = [version]$script:AppVersion
        if ($available -le $current) { return $null }
        $downloadUri = [Uri]::new([Uri]($script:LicenseServerUrl.TrimEnd('/') + '/'), [string]$manifest.downloadUrl)
        return [pscustomobject]@{ Version = [string]$manifest.version; DownloadUri = $downloadUri.AbsoluteUri; Notes = [string]$manifest.notes }
    } catch {
        return $null
    }
}

function Show-GameBoostUpdate {
    $update = Test-GameBoostUpdate
    if (-not $update) {
        Set-Status (if ($script:Language -eq 'zh-CN') { '已是最新版本' } else { 'Up to date' }) ($script:AppVersion) ([System.Drawing.Color]::FromArgb(67,190,120))
        return
    }
    $message = if ($script:Language -eq 'zh-CN') {
        '发现 GameBoost-Haxu ' + $update.Version + "。`r`n" + $update.Notes + "`r`n`r`n选择 Yes 下载更新包。解压后替换当前程序文件，再重新打开软件。"
    } else {
        "GameBoost-Haxu $($update.Version) is available.`r`n$($update.Notes)`r`n`r`nChoose Yes to download the update ZIP. Extract it, replace the current program files, then reopen the app."
    }
    $choice = [System.Windows.Forms.MessageBox]::Show($message, 'GameBoost-Haxu Update', 'YesNo', 'Information')
    if ($choice -eq 'Yes') { Start-Process $update.DownloadUri }
}

function Show-GameBoostLicenseActivationDialog {
    $dialog = New-Object System.Windows.Forms.Form
    $dialog.Text = if ($script:Language -eq 'zh-CN') { '输入专业版授权码' } else { 'Enter Pro license key' }
    $dialog.StartPosition = 'CenterParent'; $dialog.FormBorderStyle = 'FixedDialog'; $dialog.MaximizeBox = $false; $dialog.MinimizeBox = $false
    $dialog.ClientSize = New-Object System.Drawing.Size(470,154); $dialog.BackColor = [System.Drawing.Color]::FromArgb(27,35,45)
    $label = New-Object System.Windows.Forms.Label
    $label.Text = if ($script:Language -eq 'zh-CN') { '粘贴付款确认通知中的专业版授权码' } else { 'Paste the Pro license key from your payment confirmation' }
    $label.ForeColor = [System.Drawing.Color]::White; $label.Location = New-Object System.Drawing.Point(18,18); $label.AutoSize = $true; $dialog.Controls.Add($label)
    $keyBox = New-Object System.Windows.Forms.TextBox
    $keyBox.Location = New-Object System.Drawing.Point(18,48); $keyBox.Size = New-Object System.Drawing.Size(434,26); $keyBox.Text = $script:LicenseKey; $dialog.Controls.Add($keyBox)
    $saveButton = New-Object System.Windows.Forms.Button
    $saveButton.Text = if ($script:Language -eq 'zh-CN') { '保存并提示重启' } else { 'Save and restart later' }
    $saveButton.Location = New-Object System.Drawing.Point(292,96); $saveButton.Size = New-Object System.Drawing.Size(160,32); $saveButton.FlatStyle = 'Flat'; $saveButton.BackColor = [System.Drawing.Color]::FromArgb(46,115,210); $saveButton.ForeColor = [System.Drawing.Color]::White
    $saveButton.Add_Click({
        $key = $keyBox.Text.Trim().ToUpperInvariant()
        if ($key -notmatch '^(PRO|TRIAL)-[A-Z0-9]+$') {
            [System.Windows.Forms.MessageBox]::Show((if ($script:Language -eq 'zh-CN') { '授权码格式无效。' } else { 'The license key format is invalid.' }), 'GameBoost', 'OK', 'Warning') | Out-Null
            return
        }
        $script:LicenseKey = $key
        $script:LicenseServerUrl = 'http://127.0.0.1:3000'
        Save-GameBoostLicenseConfig
        [System.Windows.Forms.MessageBox]::Show((if ($script:Language -eq 'zh-CN') { '授权码已保存，升级完成。请关闭并重新打开 GameBoost 后生效。' } else { 'License key saved. Upgrade complete. Restart GameBoost for it to take effect.' }), 'GameBoost', 'OK', 'Information') | Out-Null
        $dialog.Close()
    })
    $dialog.Controls.Add($saveButton)
    $dialog.ShowDialog($form) | Out-Null
}

function New-FreeLicenseState {
    param([string]$Reason = 'no_license')
    return [pscustomobject][ordered]@{
        IsPro = $false
        Plan = 'free'
        Status = 'free'
        Reason = $Reason
        DeviceId = Get-GameBoostDeviceId
        DeviceLimit = 0
        DeviceCount = 0
        Features = Get-GameBoostFeatureSet 'free'
    }
}

function Test-GameBoostDebugging {
    try { return [System.Diagnostics.Debugger]::IsAttached } catch { return $false }
}

function Test-GameBoostFeature {
    param([string]$Feature)
    if (-not $script:LicenseState) { $script:LicenseState = New-FreeLicenseState }
    $features = $script:LicenseState.Features
    return ($features.PSObject.Properties.Name -contains $Feature -and [bool]$features.$Feature)
}

function Assert-GameBoostFeature {
    param([string]$Feature, [string]$Title)
    if (Test-GameBoostFeature $Feature) { return $true }
    $featureName = if ($Title) { $Title } else { $Feature }
    $detail = if ($script:Language -eq 'zh-CN') {
        $featureName + ' 是专业版功能。请购买专业版并完成授权验证后再使用。'
    } else {
        $featureName + ' is a Pro feature. Purchase Pro and verify the license before using it.'
    }
    Set-Status '专业版功能' $detail ([System.Drawing.Color]::FromArgb(220,160,40))
    return $false
}

function Invoke-GameBoostLicenseVerification {
    Read-GameBoostLicenseConfig
    if (-not $script:LicenseKey) {
        $script:LicenseState = New-FreeLicenseState
        return $script:LicenseState
    }

    if (Test-GameBoostDebugging) {
        $script:LicenseState = New-FreeLicenseState 'debugger_detected'
        return $script:LicenseState
    }

    $deviceId = Get-GameBoostDeviceId
    try {
        $payload = @{ licenseKey = $script:LicenseKey; deviceId = $deviceId; deviceName = $env:COMPUTERNAME }
        $response = Invoke-RestMethod -Method Post -Uri ($script:LicenseServerUrl + '/api/license') -Body ($payload | ConvertTo-Json) -ContentType 'application/json' -TimeoutSec 5
        if ($response.ok -and $response.plan -in @('pro','trial')) {
            $script:LicenseState = [pscustomobject][ordered]@{
                IsPro = $true
                Plan = [string]$response.plan
                Status = [string]$response.status
                Reason = ''
                DeviceId = $deviceId
                DeviceLimit = [int]$response.deviceLimit
                DeviceCount = [int]$response.deviceCount
                Features = $response.features
            }
            Save-GameBoostLicenseConfig
            return $script:LicenseState
        }
        $reason = if ($response.reason) { [string]$response.reason } else { 'verification_failed' }
        $script:LicenseState = New-FreeLicenseState $reason
        return $script:LicenseState
    } catch {
        $script:LicenseState = New-FreeLicenseState ('license_server_unavailable: ' + $_.Exception.Message)
        return $script:LicenseState
    }
}

function Test-GameBoostAdministrator {
    try {
        $identity = [Security.Principal.WindowsIdentity]::GetCurrent()
        $principal = New-Object Security.Principal.WindowsPrincipal($identity)
        return $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
    } catch {
        return $false
    }
}

function Restart-GameBoostElevated {
    if (Test-GameBoostAdministrator) {
        $message = if ($script:Language -eq 'zh-CN') { '当前已经是管理员权限运行。' } else { 'GameBoost is already running as administrator.' }
        [System.Windows.Forms.MessageBox]::Show($message, 'GameBoost', 'OK', 'Information') | Out-Null
        return
    }

    try {
        Start-Process -FilePath 'powershell.exe' -Verb RunAs -ArgumentList @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', $PSCommandPath) | Out-Null
        $script:AllowApplicationExit = $true
        $form.Close()
    } catch {
        $message = if ($script:Language -eq 'zh-CN') { '未获得管理员权限。网络系统策略和高级游戏策略将保持跳过。' } else { 'Elevation was not approved. System network and advanced game policies will remain unavailable.' }
        [System.Windows.Forms.MessageBox]::Show($message, 'GameBoost', 'OK', 'Warning') | Out-Null
    }
}

function Get-ActiveScheme {
    $line = (& powercfg /getactivescheme 2>$null) -join ' '
    if ($line -match '([0-9a-fA-F-]{36})') { return $matches[1].ToLowerInvariant() }
    return ''
}

function Invoke-PowerCfg {
    param([string[]]$Arguments)
    $output = & powercfg @Arguments 2>$null
    return [pscustomobject]@{ ExitCode = $LASTEXITCODE; Output = ($output -join "`n") }
}

function Get-PowerSchemes {
    $lines = & powercfg /list 2>$null
    foreach ($line in $lines) {
        if ($line -match 'GUID:\s*([0-9a-fA-F-]{36})\s+\((.+?)\)(\s+\*)?') {
            [pscustomobject]@{
                Guid = $matches[1].ToLowerInvariant()
                Name = $matches[2]
                Active = [bool]$matches[3]
            }
        }
    }
}

function Get-GpuTier {
    param([string]$GpuName)
    if (-not $GpuName) { return 'Unknown' }
    $name = $GpuName.ToUpperInvariant()
    if ($name -match 'MICROSOFT|BASIC|REMOTE|VIRTUAL') { return 'Virtual' }
    if ($name -match 'RTX\s*(4090|4080|4070|5090|5080|5070)|RX\s*(7900|7800|7700|6900|6800)|ARC\s*(B580|A770)') { return 'High' }
    if ($name -match 'RTX\s*(4060|4050|3090|3080|3070|3060|3050)|GTX\s*(1660|1650|1080|1070|1060)|RX\s*(7600|6700|6600|5700|5600)|ARC\s*(A750|A580|A380)') { return 'Mid' }
    if ($name -match 'RTX|GTX|RX|RADEON|ARC') { return 'Entry' }
    if ($name -match 'IRIS|UHD|VEGA|GRAPHICS') { return 'Integrated' }
    return 'Unknown'
}

function Get-SystemProfile {
    $cs = Get-CimInstance Win32_ComputerSystem -ErrorAction SilentlyContinue
    $cpu = Get-CimInstance Win32_Processor -ErrorAction SilentlyContinue | Select-Object -First 1
    $os = Get-CimInstance Win32_OperatingSystem -ErrorAction SilentlyContinue
    $enclosure = Get-CimInstance Win32_SystemEnclosure -ErrorAction SilentlyContinue | Select-Object -First 1
    $battery = @(Get-CimInstance Win32_Battery -ErrorAction SilentlyContinue)
    $video = @(Get-CimInstance Win32_VideoController -ErrorAction SilentlyContinue | Where-Object { $_.Name })

    $ramGb = $null
    if ($cs -and $cs.TotalPhysicalMemory) {
        $ramGb = [Math]::Round(([double]$cs.TotalPhysicalMemory / 1GB), 1)
    } else {
        $mem = Get-CimInstance Win32_PhysicalMemory -ErrorAction SilentlyContinue | Measure-Object -Property Capacity -Sum
        if ($mem.Sum) { $ramGb = [Math]::Round(([double]$mem.Sum / 1GB), 1) }
    }

    $gpu = @($video | Where-Object { $_.Name -notmatch 'Microsoft|Basic|Remote|Virtual' } | Sort-Object AdapterRAM -Descending | Select-Object -First 1)
    if (-not $gpu -and $video.Count -gt 0) { $gpu = $video[0] }
    $gpuName = if ($gpu) { [string]$gpu.Name } else { 'Unknown GPU' }
    $gpuStatus = Get-GpuStatus
    $gpuTemp = $null
    $parsedTemp = 0
    if ($gpuStatus -and [int]::TryParse([string]$gpuStatus.Temp, [ref]$parsedTemp)) { $gpuTemp = $parsedTemp }

    $chassisTypes = @()
    if ($enclosure -and $enclosure.ChassisTypes) { $chassisTypes = @($enclosure.ChassisTypes) }
    $laptopChassis = @(8,9,10,11,12,14,18,21,30,31,32)
    $isLaptop = ($cs -and $cs.PCSystemType -eq 2) -or (($chassisTypes | Where-Object { $laptopChassis -contains [int]$_ }).Count -gt 0) -or ($battery.Count -gt 0)
    $formFactor = if ($isLaptop) { 'Laptop' } else { 'Desktop' }

    return [pscustomobject]@{
        ComputerName = if ($env:COMPUTERNAME) { $env:COMPUTERNAME } else { 'Unknown' }
        Manufacturer = if ($cs) { [string]$cs.Manufacturer } else { '' }
        Model = if ($cs) { [string]$cs.Model } else { '' }
        OS = if ($os) { [string]$os.Caption } else { '' }
        FormFactor = $formFactor
        IsLaptop = [bool]$isLaptop
        CpuName = if ($cpu) { [string]$cpu.Name } else { 'Unknown CPU' }
        CpuCores = if ($cpu) { [int]$cpu.NumberOfCores } else { 0 }
        CpuThreads = if ($cpu) { [int]$cpu.NumberOfLogicalProcessors } else { 0 }
        RamGB = $ramGb
        GpuName = $gpuName
        GpuTier = (Get-GpuTier $gpuName)
        GpuTempC = $gpuTemp
    }
}

function Get-AdaptivePlan {
    param($Profile)

    $notes = New-Object System.Collections.ArrayList
    $mode = 'Performance'
    $cpuMinAc = 10
    $cpuMaxAc = 100
    $cpuBoostAc = 4
    $cpuMaxDc = 85
    $closeBackground = $false

    if ($Profile.IsLaptop) {
        $mode = 'Balanced'
        $cpuMinAc = 5
        $cpuBoostAc = 3
        $cpuMaxDc = 75
        $closeBackground = $true
        [void]$notes.Add('Laptop detected: favor stable clocks over peak spikes.')
    }

    if ($Profile.GpuTier -in @('Integrated','Entry')) {
        $mode = 'Balanced'
        $cpuBoostAc = 3
        $closeBackground = $true
        [void]$notes.Add('Entry or integrated GPU detected: reduce background load first.')
    }

    if ($Profile.GpuTempC -ne $null -and $Profile.GpuTempC -ge 86) {
        $mode = 'Cooler'
        $cpuMaxAc = 95
        $cpuBoostAc = 0
        $cpuMaxDc = 70
        $closeBackground = $true
        [void]$notes.Add('High GPU temperature detected: disable CPU boost to reduce heat soak.')
    } elseif (-not $Profile.IsLaptop -and $Profile.GpuTier -eq 'High') {
        $mode = 'Performance'
        $cpuBoostAc = 4
        $cpuMaxDc = 90
        [void]$notes.Add('High desktop GPU detected: allow a stronger AC performance profile.')
    }

    if ($Profile.RamGB -ne $null -and $Profile.RamGB -le 8) {
        $closeBackground = $true
        [void]$notes.Add('Low memory detected: background cleanup is recommended.')
    }

    if ($notes.Count -eq 0) { [void]$notes.Add('General balanced performance profile selected.') }
    $ramText = if ($Profile.RamGB -ne $null) { ($Profile.RamGB.ToString() + ' GB RAM') } else { 'RAM unknown' }

    return [pscustomobject]@{
        SchemeName = $script:PowerSchemeName
        Description = 'Adaptive game performance for this PC'
        Mode = $mode
        CpuMinAc = $cpuMinAc
        CpuMaxAc = $cpuMaxAc
        CpuBoostAc = $cpuBoostAc
        CpuMaxDc = $cpuMaxDc
        CloseBackground = $closeBackground
        Summary = ($Profile.FormFactor + ' | ' + $Profile.GpuTier + ' GPU | ' + $ramText + ' | ' + $mode)
        Notes = @($notes)
    }
}

function Get-ExtremePlan {
    param($Profile)

    $notes = New-Object System.Collections.ArrayList
    $mode = 'Extreme FPS'
    $cpuMinAc = 100
    $cpuMaxAc = 100
    $cpuBoostAc = 2
    $cpuMinDc = 50
    $cpuMaxDc = 90
    $cpuBoostDc = 4

    if ($Profile.IsLaptop) {
        $cpuMinAc = 85
        $cpuBoostAc = 4
        $cpuMaxDc = 80
        [void]$notes.Add('Laptop detected: push AC performance while avoiding constant thermal throttling.')
    } else {
        [void]$notes.Add('Desktop profile: keep CPU clocks ready and favor maximum frame delivery.')
    }

    if ($Profile.GpuTier -eq 'High') {
        $cpuBoostAc = 2
        [void]$notes.Add('High-tier GPU detected: aggressive CPU boost is allowed to feed the GPU.')
    } elseif ($Profile.GpuTier -in @('Integrated','Entry')) {
        $cpuMinAc = 75
        $cpuBoostAc = 4
        [void]$notes.Add('Entry GPU detected: prioritize background cleanup and stable CPU response.')
    }

    if ($Profile.GpuTempC -ne $null -and $Profile.GpuTempC -ge 86) {
        $cpuMinAc = [Math]::Min($cpuMinAc, 75)
        $cpuBoostAc = 4
        [void]$notes.Add('High GPU temperature detected: prevent heat saturation while staying in extreme FPS mode.')
    }

    if ($Profile.RamGB -ne $null -and $Profile.RamGB -le 16) {
        [void]$notes.Add('Memory-sensitive system: aggressive background cleanup is enabled.')
    }

    $ramText = if ($Profile.RamGB -ne $null) { ($Profile.RamGB.ToString() + ' GB RAM') } else { 'RAM unknown' }
    return [pscustomobject]@{
        SchemeName = $script:ExtremePowerSchemeName
        Description = 'Extreme low-latency game performance for this PC'
        Mode = $mode
        CpuMinAc = $cpuMinAc
        CpuMaxAc = $cpuMaxAc
        CpuBoostAc = $cpuBoostAc
        CpuMinDc = $cpuMinDc
        CpuMaxDc = $cpuMaxDc
        CpuBoostDc = $cpuBoostDc
        CloseBackground = $true
        LowLatencyTimer = $true
        DisableIdleSleep = $true
        Summary = ($Profile.FormFactor + ' | ' + $Profile.GpuTier + ' GPU | ' + $ramText + ' | ' + $mode)
        Notes = @($notes)
    }
}

function Set-WindowsGameSettings {
    param([switch]$Extreme)
    try {
        New-Item -Path 'HKCU:\System\GameConfigStore' -Force | Out-Null
        New-ItemProperty -Path 'HKCU:\System\GameConfigStore' -Name 'GameDVR_Enabled' -PropertyType DWord -Value 0 -Force | Out-Null
        New-Item -Path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\GameDVR' -Force | Out-Null
        New-ItemProperty -Path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\GameDVR' -Name 'AppCaptureEnabled' -PropertyType DWord -Value 0 -Force | Out-Null
        New-Item -Path 'HKCU:\Software\Microsoft\GameBar' -Force | Out-Null
        New-ItemProperty -Path 'HKCU:\Software\Microsoft\GameBar' -Name 'AutoGameModeEnabled' -PropertyType DWord -Value 1 -Force | Out-Null
        New-ItemProperty -Path 'HKCU:\Software\Microsoft\GameBar' -Name 'AllowAutoGameMode' -PropertyType DWord -Value 1 -Force | Out-Null
        New-ItemProperty -Path 'HKCU:\Software\Microsoft\GameBar' -Name 'ShowStartupPanel' -PropertyType DWord -Value 0 -Force | Out-Null
        New-Item -Path 'HKCU:\Software\Microsoft\DirectX\UserGpuPreferences' -Force | Out-Null
        if ($Extreme) {
            New-ItemProperty -Path 'HKCU:\System\GameConfigStore' -Name 'GameDVR_FSEBehaviorMode' -PropertyType DWord -Value 2 -Force | Out-Null
            New-ItemProperty -Path 'HKCU:\System\GameConfigStore' -Name 'GameDVR_HonorUserFSEBehaviorMode' -PropertyType DWord -Value 1 -Force | Out-Null
            New-ItemProperty -Path 'HKCU:\System\GameConfigStore' -Name 'GameDVR_DXGIHonorFSEWindowsCompatible' -PropertyType DWord -Value 1 -Force | Out-Null
            New-ItemProperty -Path 'HKCU:\Software\Microsoft\GameBar' -Name 'UseNexusForGameBarEnabled' -PropertyType DWord -Value 0 -Force | Out-Null
        }
        return $true
    } catch {
        return $false
    }
}

function Get-PlanSchemeName {
    param($Plan)
    if ($Plan -and $Plan.SchemeName) { return [string]$Plan.SchemeName }
    return $script:PowerSchemeName
}

function Get-PlanDescription {
    param($Plan)
    if ($Plan -and $Plan.Description) { return [string]$Plan.Description }
    return 'Game performance profile for this PC'
}

function Get-PlanSettingValue {
    param($Plan, [string]$Name, $Default)
    if ($Plan -and $Plan.PSObject.Properties.Name -contains $Name -and $Plan.$Name -ne $null) { return $Plan.$Name }
    return $Default
}

function Set-AdaptivePowerValues {
    param([string]$Scheme, $Plan)
    if (-not $Scheme) { return $false }

    $subProcessor = '54533251-82be-4824-96c1-47b60b740d00'
    $minProcessor = '893dee8e-2bef-41e0-89c6-b55d0929964c'
    $maxProcessor = 'bc5038f7-23e0-4960-96da-33abaf5935ec'
    $coolingPolicy = '94d3a615-a899-4ac5-ae2b-e4d8f634367f'
    $boostMode = 'be337238-0d82-4146-a960-4f3749d470c7'
    $subPcie = '501a4d13-42af-4429-9fd1-a8218c268e20'
    $pcieLinkState = 'ee12f906-d277-404b-b6da-e5fa1a576df5'
    $subWireless = '19cbb8fa-5279-450e-9fac-8a3d5fedd0c1'
    $wirelessSaving = '12bbebe6-58d6-4636-95bb-3217ef867c1a'
    $subUsb = '2a737441-1930-4402-8d77-b2bebba308a3'
    $usbSelectiveSuspend = '48e6b7a6-50f5-4782-a5d4-53bb8f07e226'
    $subDisk = '0012ee47-9041-4b5d-9b77-535fba8b1442'
    $diskIdle = '6738e2c4-e8a5-4a42-b16a-e040e769756e'
    $subSleep = '238c9fa8-0aad-41ed-83f4-97be242c8f20'
    $sleepAfter = '29f6c1db-86da-48c5-9fdb-f2b67b1f44da'
    $hibernateAfter = '9d7815a6-7ee4-497e-8888-515a05f02364'

    $cpuMinDc = if ($Plan.CpuMinDc -ne $null) { $Plan.CpuMinDc.ToString() } else { '5' }
    $cpuBoostDc = if ($Plan.CpuBoostDc -ne $null) { $Plan.CpuBoostDc.ToString() } else { '3' }
    $coolingValue = (Get-PlanSettingValue -Plan $Plan -Name 'CoolingPolicy' -Default 1).ToString()
    $pcieValue = (Get-PlanSettingValue -Plan $Plan -Name 'PcieLinkState' -Default 0).ToString()
    $wirelessValue = (Get-PlanSettingValue -Plan $Plan -Name 'WirelessSaving' -Default 0).ToString()
    $usbValue = (Get-PlanSettingValue -Plan $Plan -Name 'UsbSelectiveSuspend' -Default 0).ToString()
    $schemeName = Get-PlanSchemeName $Plan
    $schemeDescription = Get-PlanDescription $Plan

    [void](Invoke-PowerCfg @('/changename', $Scheme, $schemeName, $schemeDescription))
    $commands = @(
        @('/setacvalueindex', $Scheme, $subProcessor, $minProcessor, $Plan.CpuMinAc.ToString()),
        @('/setacvalueindex', $Scheme, $subProcessor, $maxProcessor, $Plan.CpuMaxAc.ToString()),
        @('/setdcvalueindex', $Scheme, $subProcessor, $minProcessor, $cpuMinDc),
        @('/setdcvalueindex', $Scheme, $subProcessor, $maxProcessor, $Plan.CpuMaxDc.ToString()),
        @('/setacvalueindex', $Scheme, $subProcessor, $coolingPolicy, $coolingValue),
        @('/setdcvalueindex', $Scheme, $subProcessor, $coolingPolicy, $coolingValue),
        @('/setacvalueindex', $Scheme, $subProcessor, $boostMode, $Plan.CpuBoostAc.ToString()),
        @('/setdcvalueindex', $Scheme, $subProcessor, $boostMode, $cpuBoostDc),
        @('/setacvalueindex', $Scheme, $subPcie, $pcieLinkState, $pcieValue),
        @('/setdcvalueindex', $Scheme, $subPcie, $pcieLinkState, $pcieValue),
        @('/setacvalueindex', $Scheme, $subWireless, $wirelessSaving, $wirelessValue),
        @('/setdcvalueindex', $Scheme, $subWireless, $wirelessSaving, $wirelessValue),
        @('/setacvalueindex', $Scheme, $subUsb, $usbSelectiveSuspend, $usbValue),
        @('/setdcvalueindex', $Scheme, $subUsb, $usbSelectiveSuspend, $usbValue)
    )

    if ($Plan.DisableIdleSleep -or $Plan.PSObject.Properties.Name -contains 'SleepAfterAc') {
        $diskAc = (Get-PlanSettingValue -Plan $Plan -Name 'DiskIdleAc' -Default 0).ToString()
        $diskDc = (Get-PlanSettingValue -Plan $Plan -Name 'DiskIdleDc' -Default $diskAc).ToString()
        $sleepAc = (Get-PlanSettingValue -Plan $Plan -Name 'SleepAfterAc' -Default 0).ToString()
        $sleepDc = (Get-PlanSettingValue -Plan $Plan -Name 'SleepAfterDc' -Default $sleepAc).ToString()
        $hibernateAc = (Get-PlanSettingValue -Plan $Plan -Name 'HibernateAfterAc' -Default 0).ToString()
        $hibernateDc = (Get-PlanSettingValue -Plan $Plan -Name 'HibernateAfterDc' -Default $hibernateAc).ToString()
        $commands += @(
            @('/setacvalueindex', $Scheme, $subDisk, $diskIdle, $diskAc),
            @('/setdcvalueindex', $Scheme, $subDisk, $diskIdle, $diskDc),
            @('/setacvalueindex', $Scheme, $subSleep, $sleepAfter, $sleepAc),
            @('/setdcvalueindex', $Scheme, $subSleep, $sleepAfter, $sleepDc),
            @('/setacvalueindex', $Scheme, $subSleep, $hibernateAfter, $hibernateAc),
            @('/setdcvalueindex', $Scheme, $subSleep, $hibernateAfter, $hibernateDc)
        )
    }

    $failures = 0
    foreach ($cmd in $commands) {
        $result = Invoke-PowerCfg $cmd
        if ($result.ExitCode -ne 0) { $failures++ }
    }
    return ($failures -eq 0)
}

function Ensure-GameBoostPowerScheme {
    param($Plan)

    if (-not $script:FallbackScheme) { $script:FallbackScheme = Get-ActiveScheme }
    $schemeName = Get-PlanSchemeName $Plan
    $existing = @(Get-PowerSchemes | Where-Object { $_.Name -eq $schemeName } | Select-Object -First 1)
    if ($existing.Count -gt 0) {
        [void](Set-AdaptivePowerValues -Scheme $existing[0].Guid -Plan $Plan)
        $script:PowerSchemeReady = $true
        $script:PowerSchemeMessage = $schemeName + ' is ready.'
        return $existing[0].Guid
    }

    $baseScheme = if ($script:FallbackScheme) { $script:FallbackScheme } else { '381b4222-f694-41f0-9685-ff5bb260df2e' }
    $duplicate = Invoke-PowerCfg @('/duplicatescheme', $baseScheme)
    if ($duplicate.Output -notmatch '([0-9a-fA-F-]{36})') {
        $script:PowerSchemeReady = $false
        $script:PowerSchemeMessage = 'Could not create ' + $schemeName + '; using the current Windows power profile.'
        return $baseScheme
    }

    $newScheme = $matches[1].ToLowerInvariant()
    [void](Set-AdaptivePowerValues -Scheme $newScheme -Plan $Plan)
    $script:PowerSchemeReady = $true
    $script:PowerSchemeMessage = $schemeName + ' created for this PC.'
    return $newScheme
}

function Set-GameBoostPowerActive {
    param([switch]$Extreme)

    if ($Extreme) {
        if (-not $script:ExtremePlan) { $script:ExtremePlan = Get-ExtremePlan -Profile $script:SystemProfile }
        if (-not $script:ExtremeScheme) {
            $script:ExtremeScheme = Ensure-GameBoostPowerScheme -Plan $script:ExtremePlan
        }
        $targetScheme = $script:ExtremeScheme
    } else {
        if (-not $script:OptimizedScheme) {
            $script:OptimizedScheme = Ensure-GameBoostPowerScheme -Plan $script:AdaptivePlan
        }
        $targetScheme = $script:OptimizedScheme
    }
    if (-not $targetScheme) { return $false }
    $result = Invoke-PowerCfg @('/setactive', $targetScheme)
    if ($result.ExitCode -ne 0) {
        $script:PowerSchemeMessage = 'Windows rejected the power profile switch.'
        return $false
    }
    $script:ExtremeModeActive = [bool]$Extreme
    return $true
}

function Enable-LowLatencyTimer {
    if ($script:TimerResolutionActive) { return $true }
    try {
        [void][GameBoostTimerResolution]::TimeBeginPeriod(1)
        $script:TimerResolutionActive = $true
        return $true
    } catch {
        return $false
    }
}

function Disable-LowLatencyTimer {
    if (-not $script:TimerResolutionActive) { return }
    try { [void][GameBoostTimerResolution]::TimeEndPeriod(1) } catch {}
    $script:TimerResolutionActive = $false
}

function Set-ExtremeSystemGamePolicy {
    if (-not (Test-GameBoostAdministrator)) {
        $script:ExtremeSystemPolicyState = 'requires_admin'
        return $false
    }

    try {
        $base = 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Multimedia\SystemProfile'
        New-Item -Path $base -Force -ErrorAction Stop | Out-Null
        New-ItemProperty -Path $base -Name 'SystemResponsiveness' -PropertyType DWord -Value 0 -Force -ErrorAction Stop | Out-Null
        New-ItemProperty -Path $base -Name 'NetworkThrottlingIndex' -PropertyType DWord -Value ([int]-1) -Force -ErrorAction Stop | Out-Null

        $gamesTask = Join-Path $base 'Tasks\Games'
        New-Item -Path $gamesTask -Force -ErrorAction Stop | Out-Null
        New-ItemProperty -Path $gamesTask -Name 'GPU Priority' -PropertyType DWord -Value 8 -Force -ErrorAction Stop | Out-Null
        New-ItemProperty -Path $gamesTask -Name 'Priority' -PropertyType DWord -Value 6 -Force -ErrorAction Stop | Out-Null
        New-ItemProperty -Path $gamesTask -Name 'Scheduling Category' -PropertyType String -Value 'High' -Force -ErrorAction Stop | Out-Null
        New-ItemProperty -Path $gamesTask -Name 'SFIO Priority' -PropertyType String -Value 'High' -Force -ErrorAction Stop | Out-Null
        $script:ExtremeSystemPolicyState = 'applied'
        return $true
    } catch {
        $script:ExtremeSystemPolicyState = 'failed'
        return $false
    }
}

function Stop-GameBoostBackgroundProcesses {
    param([string[]]$Names)
    $closed = 0
    if (-not $Names -or $Names.Count -eq 0) { return $closed }
    Get-Process -Name $Names -ErrorAction SilentlyContinue | ForEach-Object {
        try {
            Stop-Process -Id $_.Id -Force -ErrorAction Stop
            $closed++
        } catch {}
    }
    return $closed
}

function Set-GameProcessPriority {
    param($Game, [int]$WaitSeconds = 1)
    if (-not $Game -or -not $Game.Exe) { return $false }

    $processName = [IO.Path]::GetFileNameWithoutExtension($Game.Exe)
    $deadline = (Get-Date).AddSeconds($WaitSeconds)
    do {
        $processes = @(Get-Process -Name $processName -ErrorAction SilentlyContinue)
        if ($processes.Count -gt 0) {
            $updated = $false
            foreach ($process in $processes) {
                try {
                    $process.PriorityClass = 'High'
                    $updated = $true
                } catch {}
            }
            return $updated
        }
        if ($WaitSeconds -le 1) { break }
        Start-Sleep -Milliseconds 500
    } while ((Get-Date) -lt $deadline)
    return $false
}

function Set-RunningGamePriorities {
    param([object[]]$Games)
    $count = 0
    foreach ($game in $Games) {
        if (Set-GameProcessPriority -Game $game -WaitSeconds 1) { $count++ }
    }
    return $count
}

function Get-NormalizedPath {
    param([string]$Path)
    if (-not $Path) { return '' }
    try { return [IO.Path]::GetFullPath($Path).TrimEnd([IO.Path]::DirectorySeparatorChar, [IO.Path]::AltDirectorySeparatorChar) } catch { return '' }
}

function Get-NormalizedProcessBaseName {
    param([string]$Name)
    if (-not $Name) { return '' }
    return (([IO.Path]::GetFileNameWithoutExtension($Name) -replace '[^a-zA-Z0-9]', '').ToLowerInvariant())
}

function Test-SmartGlobalGameCandidate {
    param($Game)
    if (-not $Game) { return $false }
    $name = [string]$Game.Name
    $appId = [string]$Game.AppId
    if ($appId -in @('431960')) { return $false }
    if ($name -match '(?i)wallpaper\s*engine|lossless\s*scaling|steamvr|soundpad|benchmark|3dmark') { return $false }
    return $true
}

function Get-RunningGameProcesses {
    param([object[]]$Games)

    if (-not $Games -or $Games.Count -eq 0) { return @() }
    $candidateGames = @($Games | Where-Object { Test-SmartGlobalGameCandidate $_ })
    if ($candidateGames.Count -eq 0) { return @() }

    $processes = @(Get-CimInstance Win32_Process -ErrorAction SilentlyContinue)
    if ($processes.Count -eq 0) { return @() }

    $seen = @{}
    foreach ($game in $candidateGames) {
        $gameExe = Get-NormalizedPath $game.Exe
        $installRoot = Get-NormalizedPath $game.InstallPath
        $gameNameKey = Get-NormalizedProcessBaseName $game.Name
        $gameExeKey = Get-NormalizedProcessBaseName $game.Exe
        if ($installRoot) { $installRoot = $installRoot.TrimEnd([IO.Path]::DirectorySeparatorChar, [IO.Path]::AltDirectorySeparatorChar) + [IO.Path]::DirectorySeparatorChar }
        if ($installRoot) { $installRoot = $installRoot + '\' }

        if ($installRoot) { $installRoot = $installRoot.TrimEnd([IO.Path]::DirectorySeparatorChar, [IO.Path]::AltDirectorySeparatorChar) + [IO.Path]::DirectorySeparatorChar }

        foreach ($process in $processes) {
            $processPath = Get-NormalizedPath ([string]$process.ExecutablePath)
            $processNameKey = Get-NormalizedProcessBaseName ([string]$process.Name)
            if (-not $processPath -and -not $processNameKey) { continue }

            $matched = $false
            if ($gameExe -and $processPath.Equals($gameExe, [System.StringComparison]::OrdinalIgnoreCase)) {
                $matched = $true
            } elseif ($installRoot -and (($processPath + '\').StartsWith($installRoot, [System.StringComparison]::OrdinalIgnoreCase))) {
                $matched = $true
            }

            if (-not $matched -and $processNameKey -and ($processNameKey -eq $gameExeKey -or $processNameKey -eq $gameNameKey)) {
                # Protected processes may not expose ExecutablePath through CIM to a standard user.
                $matched = $true
            }

            if ($matched -and -not $seen.ContainsKey($process.ProcessId)) {
                $seen[$process.ProcessId] = $true
                [pscustomobject]@{
                    Game = $game
                    ProcessId = [int]$process.ProcessId
                    ProcessName = [string]$process.Name
                    ExecutablePath = [string]$process.ExecutablePath
                }
            }
        }
    }
}

function Set-ProcessHighPriorityById {
    param([int]$ProcessId)
    try {
        $process = Get-Process -Id $ProcessId -ErrorAction Stop
        $process.PriorityClass = 'High'
        return $true
    } catch {
        return $false
    }
}

function Get-GpuStatus {
    try {
        $line = (& nvidia-smi --query-gpu=temperature.gpu,utilization.gpu,power.draw --format=csv,noheader,nounits 2>$null | Select-Object -First 1)
        if ($line) {
            $parts = $line.Split(',') | ForEach-Object { $_.Trim() }
            return [pscustomobject]@{ Temp = $parts[0]; Load = $parts[1]; Power = $parts[2] }
        }
    } catch {}
    return $null
}

function Get-PrimaryRunningGame {
    $running = @(Get-RunningGameProcesses @($script:Games))
    if ($running.Count -gt 0) { return $running[0] }
    return $null
}

function Ensure-MetricsFolder {
    if (-not (Test-Path -LiteralPath $script:MetricsFolder)) {
        New-Item -ItemType Directory -Path $script:MetricsFolder -Force | Out-Null
    }
}

function Start-MetricsLogging {
    param([string]$GameName = '', [switch]$Automatic)
    Ensure-MetricsFolder
    $script:MetricsFile = Join-Path $script:MetricsFolder ('GameBoost-' + (Get-Date -Format 'yyyyMMdd-HHmmss') + '.csv')
    'Timestamp,Game,Mode,PowerScheme,GpuTempC,GpuLoadPct,GpuPowerW,FPS,PingMs,TimerResolution,SmartGlobal,ThermalGuard,SessionType' | Set-Content -LiteralPath $script:MetricsFile -Encoding UTF8
    $script:MetricsLoggingEnabled = $true
    $script:MetricsAutoSession = [bool]$Automatic
    $script:MetricsSessionGame = $GameName
    [void]$script:MetricsSamples.Clear()
    $prefix = if ($Automatic) { if ($script:Language -eq 'zh-CN') { '游戏已启动，自动记录：' } else { 'Game detected, auto logging: ' } } else { '' }
    Set-Status (T 'MetricsOn') ($prefix + $script:MetricsFile) ([System.Drawing.Color]::FromArgb(67,190,120))
    Set-MetricsButtonState
    Update-AdvancedLabels
}

function Stop-MetricsLogging {
    $script:MetricsLoggingEnabled = $false
    $script:MetricsAutoSession = $false
    $script:MetricsSessionGame = ''
    $detail = if ($script:MetricsFile) { 'Saved: ' + $script:MetricsFile } else { 'No active log file.' }
    Set-Status (T 'MetricsOff') $detail ([System.Drawing.Color]::FromArgb(150,158,170))
    Set-MetricsButtonState
    Update-AdvancedLabels
}

function Toggle-MetricsLogging {
    if (-not (Assert-GameBoostFeature 'metricsLogging' (T 'Metrics'))) { return }
    if ($script:MetricsLoggingEnabled) { Stop-MetricsLogging } else { Start-MetricsLogging }
}

function Get-NetworkLatencyMs {
    try {
        if ($script:LatencyTask -and $script:LatencyTask.IsCompleted) {
            try {
                $reply = $script:LatencyTask.GetAwaiter().GetResult()
                if ($reply -and $reply.Status -eq [System.Net.NetworkInformation.IPStatus]::Success) { $script:LastPingMs = [int]$reply.RoundtripTime }
            } catch {}
            if ($script:LatencyPing) { $script:LatencyPing.Dispose() }
            $script:LatencyPing = $null; $script:LatencyTask = $null
        }
        if (-not $script:LatencyTask) {
            $script:LatencyPing = New-Object System.Net.NetworkInformation.Ping
            $script:LatencyTask = $script:LatencyPing.SendPingAsync($script:LatencyTarget, 700)
        }
    } catch {}
    return $script:LastPingMs
}

function Get-GameFps {
    # FPS needs a frame-present telemetry source such as PresentMon. Never estimate it from CPU or GPU load.
    return $null
}

function Update-AutoMetricsSession {
    param($Match)
    if ($Match) {
        $gameName = [string]$Match.Game.Name
        if (-not $script:MetricsLoggingEnabled) {
            Start-MetricsLogging -GameName $gameName -Automatic
        } elseif ($script:MetricsAutoSession -and $script:MetricsSessionGame -ne $gameName) {
            Stop-MetricsLogging
            Start-MetricsLogging -GameName $gameName -Automatic
        }
    } elseif ($script:MetricsLoggingEnabled -and $script:MetricsAutoSession) {
        Stop-MetricsLogging
    }
}

function Write-MetricsSample {
    param($Gpu, [string]$ActiveScheme, $Match, $PingMs)
    if (-not $script:MetricsLoggingEnabled -or -not $script:MetricsFile) { return }

    try {
        $gameName = if ($match) { [string]$match.Game.Name } elseif ($script:SelectedGame) { [string]$script:SelectedGame.Name } else { '' }
        $mode = if ($script:ExtremeModeActive) { 'Extreme' } elseif ($script:SmartGlobalEnabled) { 'SmartGlobal' } else { 'Normal' }
        $temp = if ($Gpu) { [string]$Gpu.Temp } else { '' }
        $load = if ($Gpu) { [string]$Gpu.Load } else { '' }
        $power = if ($Gpu) { [string]$Gpu.Power } else { '' }
        $fps = Get-GameFps
        $sessionType = if ($script:MetricsAutoSession) { 'Auto' } else { 'Manual' }
        $line = @(
            (Get-Date).ToString('s'),
            ('"' + ($gameName -replace '"','""') + '"'),
            $mode,
            $ActiveScheme,
            $temp,
            $load,
            $power,
            $fps,
            $PingMs,
            ([int]$script:TimerResolutionActive),
            ([int]$script:SmartGlobalEnabled),
            ([int]$script:ThermalGuardEnabled),
            $sessionType
        ) -join ','
        Add-Content -LiteralPath $script:MetricsFile -Value $line -Encoding UTF8
        [void]$script:MetricsSamples.Add([pscustomobject]@{ Timestamp=(Get-Date); GpuTempC=$Gpu.Temp; FPS=$fps; PingMs=$PingMs })
        while ($script:MetricsSamples.Count -gt 180) { $script:MetricsSamples.RemoveAt(0) }
        Update-MetricsChart
    } catch {}
}

function Add-MetricsChartSeries {
    param($Chart, [string]$Name, [string]$Title, [int]$Top, [System.Drawing.Color]$Color)
    $area = New-Object System.Windows.Forms.DataVisualization.Charting.ChartArea $Name
    $area.Position = New-Object System.Windows.Forms.DataVisualization.Charting.ElementPosition(5,$Top,90,28)
    $area.AxisX.LabelStyle.Format = 'HH:mm:ss'; $area.AxisX.MajorGrid.LineColor = [System.Drawing.Color]::FromArgb(45,70,80,90)
    $area.AxisY.MajorGrid.LineColor = [System.Drawing.Color]::FromArgb(45,70,80,90); $area.AxisY.Title = $Title
    $area.BackColor = [System.Drawing.Color]::FromArgb(20,26,34)
    [void]$Chart.ChartAreas.Add($area)
    $series = New-Object System.Windows.Forms.DataVisualization.Charting.Series $Name
    $series.ChartType = [System.Windows.Forms.DataVisualization.Charting.SeriesChartType]::Line
    $series.BorderWidth = 2; $series.Color = $Color; $series.ChartArea = $Name; $series.XValueType = [System.Windows.Forms.DataVisualization.Charting.ChartValueType]::DateTime
    [void]$Chart.Series.Add($series)
}

function Update-MetricsChart {
    if (-not $script:MetricsChart -or $script:MetricsChart.IsDisposed) { return }
    foreach ($name in @('Temperature','FPS','Latency')) { $script:MetricsChart.Series[$name].Points.Clear() }
    foreach ($sample in $script:MetricsSamples) {
        if ($sample.GpuTempC -ne $null -and "$($sample.GpuTempC)" -ne '') { [void]$script:MetricsChart.Series['Temperature'].Points.AddXY($sample.Timestamp,[double]$sample.GpuTempC) }
        if ($sample.FPS -ne $null -and "$($sample.FPS)" -ne '') { [void]$script:MetricsChart.Series['FPS'].Points.AddXY($sample.Timestamp,[double]$sample.FPS) }
        if ($sample.PingMs -ne $null -and "$($sample.PingMs)" -ne '') { [void]$script:MetricsChart.Series['Latency'].Points.AddXY($sample.Timestamp,[double]$sample.PingMs) }
    }
    $script:MetricsChart.Titles.Clear()
    $fpsState = if ($script:MetricsChart.Series['FPS'].Points.Count -eq 0) { if ($script:Language -eq 'zh-CN') { 'FPS 需要 PresentMon 数据源' } else { 'FPS requires PresentMon telemetry' } } else { '' }
    [void]$script:MetricsChart.Titles.Add($fpsState)
    $script:MetricsChart.Invalidate()
}

function Show-MetricsChart {
    if ($script:MetricsChartForm -and -not $script:MetricsChartForm.IsDisposed) { $script:MetricsChartForm.Activate(); return }
    $dialog = New-Object System.Windows.Forms.Form
    $dialog.Text = if ($script:Language -eq 'zh-CN') { 'GameBoost - 游戏会话曲线' } else { 'GameBoost - Session Charts' }
    $dialog.Size = New-Object System.Drawing.Size(900,680); $dialog.MinimumSize = New-Object System.Drawing.Size(720,520)
    $dialog.BackColor = [System.Drawing.Color]::FromArgb(18,24,32); $dialog.ForeColor = [System.Drawing.Color]::White
    $chart = New-Object System.Windows.Forms.DataVisualization.Charting.Chart
    $chart.Dock = 'Fill'; $chart.BackColor = $dialog.BackColor; $chart.Legends.Clear()
    Add-MetricsChartSeries -Chart $chart -Name 'Temperature' -Title 'GPU C' -Top 5 -Color ([System.Drawing.Color]::FromArgb(235,112,80))
    Add-MetricsChartSeries -Chart $chart -Name 'FPS' -Title 'FPS' -Top 36 -Color ([System.Drawing.Color]::FromArgb(74,173,232))
    Add-MetricsChartSeries -Chart $chart -Name 'Latency' -Title 'Ping ms' -Top 67 -Color ([System.Drawing.Color]::FromArgb(85,200,140))
    $dialog.Controls.Add($chart); $script:MetricsChartForm = $dialog; $script:MetricsChart = $chart
    $dialog.Add_FormClosed({ $script:MetricsChartForm = $null; $script:MetricsChart = $null })
    Update-MetricsChart
    $dialog.Show()
}

function Read-LearningProfiles {
    if (-not (Test-Path -LiteralPath $script:LearningFile)) { return @{} }
    try {
        $json = Get-Content -LiteralPath $script:LearningFile -Raw -Encoding UTF8 | ConvertFrom-Json
        $table = @{}
        foreach ($property in $json.PSObject.Properties) {
            $table[$property.Name] = $property.Value
        }
        return $table
    } catch {
        return @{}
    }
}

function Save-LearningProfiles {
    param([hashtable]$Profiles)
    try {
        $Profiles | ConvertTo-Json -Depth 5 | Set-Content -LiteralPath $script:LearningFile -Encoding UTF8
    } catch {}
}

function Get-GameProfileKey {
    param($Game)
    if (-not $Game) { return '' }
    return ([string]$Game.Name).ToLowerInvariant()
}

function New-GameLearningProfile {
    param($Game)
    return [pscustomobject][ordered]@{
        Name = [string]$Game.Name
        AppId = [string]$Game.AppId
        PreferredMode = 'Auto'
        NetworkOptimized = $false
        CompetitiveMode = $false
        ThermalLimitC = 0
        LastRestoreReason = ''
        LastPreflight = ''
        Sessions = 0
        ExtremeSessions = 0
        NormalSessions = 0
        ThermalDownshifts = 0
        LastMode = ''
        LastGpuTempC = ''
        LastSeen = ''
    }
}

function Ensure-GameLearningProfileShape {
    param($Game, $Profile)
    if (-not $Profile) { return (New-GameLearningProfile $Game) }
    $defaults = New-GameLearningProfile $Game
    foreach ($property in $defaults.PSObject.Properties) {
        if ($Profile.PSObject.Properties.Name -notcontains $property.Name) {
            $Profile | Add-Member -MemberType NoteProperty -Name $property.Name -Value $property.Value -Force
        }
    }
    return $Profile
}

function Get-GameLearningProfile {
    param($Game)
    if (-not $Game) { return $null }
    $profiles = Read-LearningProfiles
    $key = Get-GameProfileKey $Game
    if (-not $profiles.ContainsKey($key)) {
        $profiles[$key] = New-GameLearningProfile $Game
        Save-LearningProfiles $profiles
    }
    $profiles[$key] = Ensure-GameLearningProfileShape -Game $Game -Profile $profiles[$key]
    return $profiles[$key]
}

function Set-GamePreferredMode {
    param($Game, [string]$Mode)
    if (-not $Game) { return $false }
    if ($Mode -notin @('Auto','Normal','Extreme','Competitive')) { $Mode = 'Auto' }
    $profiles = Read-LearningProfiles
    $key = Get-GameProfileKey $Game
    if (-not $profiles.ContainsKey($key)) { $profiles[$key] = New-GameLearningProfile $Game }
    $profiles[$key] = Ensure-GameLearningProfileShape -Game $Game -Profile $profiles[$key]
    $profiles[$key].PreferredMode = $Mode
    Save-LearningProfiles $profiles
    return $true
}

function Get-GamePreferredMode {
    param($Game)
    if (-not $Game) { return 'Auto' }
    $profile = Get-GameLearningProfile $Game
    if ($profile -and $profile.PreferredMode -in @('Auto','Normal','Extreme','Competitive')) { return [string]$profile.PreferredMode }
    return 'Auto'
}

function Get-EffectiveGameMode {
    param($Game)
    $mode = Get-GamePreferredMode $Game
    if (-not (Test-GameBoostFeature 'extremeOptimization') -and $mode -in @('Auto','Extreme','Competitive')) { return 'Normal' }
    if ($mode -eq 'Competitive') { return 'Extreme' }
    if ($mode -ne 'Auto') { return $mode }

    $profile = Get-GameLearningProfile $Game
    if ($profile -and [int]$profile.ThermalDownshifts -ge 2 -and $script:SystemProfile.IsLaptop) { return 'Normal' }
    if ($script:SystemProfile.GpuTempC -ne $null -and $script:SystemProfile.GpuTempC -ge 84 -and $script:SystemProfile.IsLaptop) { return 'Normal' }
    return 'Extreme'
}

function Update-GameLearningProfile {
    param(
        $Game,
        [string]$Event,
        $Gpu
    )
    if (-not $Game) { return }
    $profiles = Read-LearningProfiles
    $key = Get-GameProfileKey $Game
    if (-not $profiles.ContainsKey($key)) {
        $profiles[$key] = New-GameLearningProfile $Game
    }
    $profiles[$key] = Ensure-GameLearningProfileShape -Game $Game -Profile $profiles[$key]

    $profile = $profiles[$key]
    if ($Event -eq 'SessionStart') {
        $profile.Sessions = [int]$profile.Sessions + 1
        if ($script:ExtremeModeActive) { $profile.ExtremeSessions = [int]$profile.ExtremeSessions + 1 }
        else { $profile.NormalSessions = [int]$profile.NormalSessions + 1 }
    } elseif ($Event -eq 'ThermalDownshift') {
        $profile.ThermalDownshifts = [int]$profile.ThermalDownshifts + 1
    } elseif ($Event -eq 'NetworkOptimized') {
        $profile.NetworkOptimized = $true
    } elseif ($Event -eq 'Restore') {
        $profile.LastRestoreReason = [string]$script:LastRestoreReason
    } elseif ($Event -eq 'Preflight') {
        $profile.LastPreflight = (Get-Date).ToString('s')
    }
    $profile.LastMode = if ($script:ExtremeModeActive) { 'Extreme' } elseif ($script:SmartGlobalEnabled) { 'SmartGlobal' } else { 'Normal' }
    if ($Gpu) { $profile.LastGpuTempC = [string]$Gpu.Temp }
    $profile.LastSeen = (Get-Date).ToString('s')
    Save-LearningProfiles $profiles
}

function Get-CompetitiveThermalLimit {
    param($Game)
    $profile = Get-GameLearningProfile $Game
    if ($profile -and [int]$profile.ThermalLimitC -ge 75 -and [int]$profile.ThermalLimitC -le 92) { return [int]$profile.ThermalLimitC }
    if ($Game -and (Get-GamePreferredMode $Game) -eq 'Competitive' -and $script:SystemProfile.IsLaptop) { return 84 }
    return $script:ThermalLimitC
}

function Show-CompetitivePreflight {
    if (-not (Assert-GameBoostFeature 'gameProfiles' '竞技预检')) { return }
    $game = $script:SelectedGame
    if (-not $game) { $running = Get-PrimaryRunningGame; if ($running) { $game = $running.Game } }
    $gpu = Get-GpuStatus
    $checks = New-Object System.Collections.ArrayList
    if ($game) { [void]$checks.Add('游戏：' + $game.Name + ' 已选择') } else { [void]$checks.Add('游戏：未选择，请先选游戏') }
    if ($game -and ($game.Exe -or ($game.Source -eq 'Steam' -and $game.AppId))) { [void]$checks.Add('启动：可用') } elseif ($game) { [void]$checks.Add('启动：需要指定 EXE') }
    if (Test-GameBoostAdministrator) { [void]$checks.Add('权限：管理员增强可用') } else { [void]$checks.Add('权限：普通模式可用，极限系统策略需管理员') }
    if ($gpu -and $gpu.Temp -ne '') {
        $limit = Get-CompetitiveThermalLimit $game
        $thermal = if ([int]$gpu.Temp -ge $limit) { '温度：' + $gpu.Temp + ' C，建议普通模式或先降温' } else { '温度：' + $gpu.Temp + ' C，低于 ' + $limit + ' C 阈值' }
        [void]$checks.Add($thermal)
    } else { [void]$checks.Add('温度：未检测到独显传感器') }
    $scheme = Get-ActiveScheme
    [void]$checks.Add('电源：' + $(if ($scheme) { '已读取当前方案' } else { '无法读取当前方案' }))
    $detail = ($checks -join '；')
    if ($game) { Update-GameLearningProfile -Game $game -Event 'Preflight' -Gpu $gpu }
    $script:LastAdviceSummary = if ($game) { (Get-GameAdvice $game) } else { $detail }
    Set-Status '竞技预检完成' $detail ([System.Drawing.Color]::FromArgb(67,190,120))
    Update-AdvancedLabels
}

function Get-NetworkProbe {
    $targets = @('223.5.5.5', '114.114.114.114', '8.8.8.8')
    $rows = New-Object System.Collections.ArrayList
    foreach ($target in $targets) {
        try {
            $samples = @(Test-Connection -ComputerName $target -Count 4 -ErrorAction SilentlyContinue)
            $received = $samples.Count
            $loss = [Math]::Round(((4 - $received) / 4) * 100, 0)
            $avg = ''
            if ($received -gt 0) {
                $avg = [Math]::Round((($samples | Measure-Object -Property ResponseTime -Average).Average), 1).ToString()
            }
            [void]$rows.Add([pscustomobject]@{ Target=$target; Received=$received; LossPct=$loss; AvgMs=$avg })
        } catch {
            [void]$rows.Add([pscustomobject]@{ Target=$target; Received=0; LossPct=100; AvgMs='' })
        }
    }
    return @($rows)
}

function Format-NetworkProbe {
    param([object[]]$Rows)
    if ($script:Language -eq 'zh-CN') {
        return (@($Rows | ForEach-Object {
            $avg = if ($_.AvgMs) { $_.AvgMs } else { '-' }
            $_.Target + ' 延迟 ' + $avg + 'ms / 丢包 ' + $_.LossPct + '%'
        }) -join '；')
    }
    return (@($Rows | ForEach-Object {
        $avg = if ($_.AvgMs) { $_.AvgMs } else { '-' }
        $_.Target + ' avg ' + $avg + 'ms / loss ' + $_.LossPct + '%'
    }) -join '; ')
}

function Run-NetworkCheck {
    $rows = Get-NetworkProbe
    $script:LastNetworkSummary = Format-NetworkProbe $rows
    Set-Status (T 'NetworkDone') $script:LastNetworkSummary ([System.Drawing.Color]::FromArgb(67,190,120))
    Update-AdvancedLabels
}

function Invoke-NetworkGameOptimization {
    if (-not (Assert-GameBoostFeature 'networkOptimization' (T 'Network'))) { return }
    if ($script:NetworkJob -and $script:NetworkJob.State -eq 'Running') { return }
    $script:NetworkJob = Start-Job -ScriptBlock {
        $actions = New-Object System.Collections.ArrayList
        try { & ipconfig /flushdns | Out-Null; [void]$actions.Add('DNS cache flushed') } catch {}
        $netshCommands = @(
            @('int','tcp','set','global','autotuninglevel=normal'),
            @('int','tcp','set','global','rss=enabled'),
            @('int','tcp','set','global','ecncapability=disabled')
        )
        foreach ($cmd in $netshCommands) {
            try { & netsh @cmd | Out-Null; if ($LASTEXITCODE -eq 0) { [void]$actions.Add(('netsh ' + ($cmd -join ' '))) } } catch {}
        }
        $targets = @('223.5.5.5', '114.114.114.114', '8.8.8.8')
        $rows = New-Object System.Collections.ArrayList
        foreach ($target in $targets) {
            $samples = New-Object System.Collections.ArrayList
            $ping = New-Object System.Net.NetworkInformation.Ping
            foreach ($attempt in 1..2) {
                try { $reply = $ping.Send($target, 800); if ($reply.Status -eq 'Success') { [void]$samples.Add([int]$reply.RoundtripTime) } } catch {}
            }
            $received = $samples.Count
            $loss = [Math]::Round(((2 - $received) / 2) * 100, 0)
            $avg = if ($received -gt 0) { [Math]::Round((($samples | Measure-Object -Average).Average), 1).ToString() } else { '' }
            [void]$rows.Add([pscustomobject]@{ Target=$target; Received=$received; LossPct=$loss; AvgMs=$avg })
        }
        [pscustomobject]@{ Actions=@($actions); Rows=@($rows) }
    }
    $networkButton.Enabled = $false
    $networkButton.Text = if ($script:Language -eq 'zh-CN') { '检测中...' } else { 'WORKING...' }
    $workingTitle = if ($script:Language -eq 'zh-CN') { '网络优化进行中' } else { 'NETWORK OPTIMIZATION' }
    $workingDetail = if ($script:Language -eq 'zh-CN') { '正在后台刷新 DNS、应用网络策略并检测延迟。界面可继续操作。' } else { 'Refreshing DNS, applying network policy, and probing latency in the background.' }
    Set-Status $workingTitle $workingDetail ([System.Drawing.Color]::FromArgb(220,160,40))
}

function Complete-NetworkGameOptimization {
    if (-not $script:NetworkJob -or $script:NetworkJob.State -notin @('Completed','Failed','Stopped')) { return }
    $result = @(Receive-Job -Job $script:NetworkJob -ErrorAction SilentlyContinue | Select-Object -First 1)
    Remove-Job -Job $script:NetworkJob -Force -ErrorAction SilentlyContinue
    $script:NetworkJob = $null
    $networkButton.Enabled = $true
    $networkButton.Text = T 'Network'
    if ($result.Count -eq 0) {
        $failureDetail = if ($script:Language -eq 'zh-CN') { '网络优化未返回结果，请以管理员身份重试。' } else { 'Network optimization returned no result. Retry as administrator.' }
        Set-Status (T 'NetworkDone') $failureDetail ([System.Drawing.Color]::FromArgb(205,80,55))
        return
    }
    $script:LastNetworkSummary = Format-NetworkProbe @($result[0].Rows)
    if ($script:SelectedGame) { Update-GameLearningProfile -Game $script:SelectedGame -Event 'NetworkOptimized' -Gpu (Get-GpuStatus) }
    $actionText = if (@($result[0].Actions).Count -gt 0) { (@($result[0].Actions) -join '; ') } else { 'No elevated network changes were accepted' }
    $detail = if ($script:Language -eq 'zh-CN') { '已执行低风险网络优化：' + $actionText + '。检测：' + $script:LastNetworkSummary } else { 'Low-risk network optimization applied: ' + $actionText + '. Probe: ' + $script:LastNetworkSummary }
    Set-Status (T 'NetworkDone') $detail ([System.Drawing.Color]::FromArgb(67,190,120))
    Update-AdvancedLabels
}

function Get-GameAdvice {
    param($Game)
    $profile = $script:SystemProfile
    $lines = New-Object System.Collections.ArrayList
    if (-not $Game) {
        if ($script:Language -eq 'zh-CN') { return '先选择一个游戏，或开启智能全局让程序自动识别运行中的游戏。' }
        return 'Select a game first, or enable auto global detection.'
    }

    $learnedProfiles = Read-LearningProfiles
    $learned = $null
    $learnedKey = ([string]$Game.Name).ToLowerInvariant()
    if ($learnedProfiles.ContainsKey($learnedKey)) { $learned = $learnedProfiles[$learnedKey] }

    if ($script:Language -eq 'zh-CN') {
        $recommendedMode = if ($profile.IsLaptop) { '最佳优化 + 温控保护' } else { '最佳优化' }
        [void]$lines.Add('推荐模式：' + $recommendedMode + '。')
        if ($profile.GpuTier -in @('Integrated','Entry','Mid')) { [void]$lines.Add('画质建议：优先降低阴影、后期处理和视距，纹理按显存余量保留。') }
        if ($profile.RamGB -ne $null -and $profile.RamGB -le 16) { [void]$lines.Add('内存建议：游戏前关闭浏览器、网盘、音乐和聊天常驻。') }
        if ($profile.GpuTempC -ne $null -and $profile.GpuTempC -ge 82) { [void]$lines.Add('温度建议：当前 GPU 温度偏高，保持温控保护开启。') }
        if ($learned -and [int]$learned.ThermalDownshifts -gt 0) { [void]$lines.Add('学习结果：这个游戏曾触发温控降档，建议保持散热和温控保护。') }
        if ($Game.Name -match 'PUBG') { [void]$lines.Add('PUBG 建议：全屏独占、关闭录像回放，优先追求 1% Low 稳定。') }
    } else {
        $recommendedMode = if ($profile.IsLaptop) { 'Extreme + thermal guard' } else { 'Extreme' }
        [void]$lines.Add('Recommended mode: ' + $recommendedMode + '.')
        if ($profile.GpuTier -in @('Integrated','Entry','Mid')) { [void]$lines.Add('Graphics: lower shadows, post-processing, and view distance first.') }
        if ($profile.RamGB -ne $null -and $profile.RamGB -le 16) { [void]$lines.Add('Memory: close browsers, sync tools, music, and chat apps before play.') }
        if ($profile.GpuTempC -ne $null -and $profile.GpuTempC -ge 82) { [void]$lines.Add('Thermals: GPU is warm, keep thermal guard enabled.') }
        if ($learned -and [int]$learned.ThermalDownshifts -gt 0) { [void]$lines.Add('Learning: this game has triggered thermal downshift before.') }
        if ($Game.Name -match 'PUBG') { [void]$lines.Add('PUBG: use exclusive fullscreen, disable replay capture, and tune for 1% low stability.') }
    }

    return (@($lines) -join ' ')
}

function Show-GameAdvice {
    $target = $script:SelectedGame
    if (-not $target) {
        $running = Get-PrimaryRunningGame
        if ($running) { $target = $running.Game }
    }
    $script:LastAdviceSummary = Get-GameAdvice $target
    Set-Status (T 'AdviceReady') $script:LastAdviceSummary ([System.Drawing.Color]::FromArgb(220,160,40))
    Update-AdvancedLabels
}

function Open-GameProfileDialog {
    if (-not (Assert-GameBoostFeature 'gameProfiles' (T 'Profile'))) { return }
    if (-not $script:SelectedGame) {
        Set-Status (T 'SelectGame') (T 'SelectGameDetail') ([System.Drawing.Color]::FromArgb(220,160,40))
        return
    }

    $dialog = New-Object System.Windows.Forms.Form
    $dialog.Text = if ($script:Language -eq 'zh-CN') { '游戏画像' } else { 'Game Profile' }
    $dialog.Size = New-Object System.Drawing.Size(360,220)
    $dialog.StartPosition = 'CenterParent'
    $dialog.BackColor = [System.Drawing.Color]::FromArgb(18,24,32)
    $dialog.ForeColor = [System.Drawing.Color]::White
    $dialog.FormBorderStyle = 'FixedDialog'
    $dialog.MaximizeBox = $false
    $dialog.MinimizeBox = $false

    $nameLabel = New-Object System.Windows.Forms.Label
    $nameLabel.Text = $script:SelectedGame.Name
    $nameLabel.Location = New-Object System.Drawing.Point(22,20)
    $nameLabel.Size = New-Object System.Drawing.Size(300,28)
    $nameLabel.Font = New-Object System.Drawing.Font('Microsoft YaHei UI',10,[System.Drawing.FontStyle]::Bold)
    $dialog.Controls.Add($nameLabel)

    $modeLabel = New-Object System.Windows.Forms.Label
    $modeLabel.Text = if ($script:Language -eq 'zh-CN') { '智能全局模式' } else { 'Auto global mode' }
    $modeLabel.Location = New-Object System.Drawing.Point(22,64)
    $modeLabel.AutoSize = $true
    $dialog.Controls.Add($modeLabel)

    $modeBox = New-Object System.Windows.Forms.ComboBox
    $modeBox.DropDownStyle = 'DropDownList'
    [void]$modeBox.Items.AddRange(@('Auto','Normal','Extreme','Competitive'))
    $modeBox.SelectedItem = Get-GamePreferredMode $script:SelectedGame
    if ($modeBox.SelectedIndex -lt 0) { $modeBox.SelectedIndex = 0 }
    $modeBox.Location = New-Object System.Drawing.Point(150,60)
    $modeBox.Size = New-Object System.Drawing.Size(160,28)
    $dialog.Controls.Add($modeBox)

    $hint = New-Object System.Windows.Forms.Label
    $hint.Text = if ($script:Language -eq 'zh-CN') { 'Auto 会按温度和历史记录决定普通/最佳。' } else { 'Auto chooses normal or extreme from thermals and history.' }
    $hint.Location = New-Object System.Drawing.Point(22,104)
    $hint.Size = New-Object System.Drawing.Size(300,32)
    $hint.ForeColor = [System.Drawing.Color]::FromArgb(190,178,150)
    $dialog.Controls.Add($hint)

    $save = New-Object System.Windows.Forms.Button
    $save.Text = if ($script:Language -eq 'zh-CN') { '保存' } else { 'SAVE' }
    $save.Location = New-Object System.Drawing.Point(212,142)
    $save.Size = New-Object System.Drawing.Size(98,34)
    $save.FlatStyle = 'Flat'
    $save.BackColor = [System.Drawing.Color]::FromArgb(46,115,210)
    $save.ForeColor = [System.Drawing.Color]::White
    $dialog.Controls.Add($save)
    $save.Add_Click({
        [void](Set-GamePreferredMode -Game $script:SelectedGame -Mode ([string]$modeBox.SelectedItem))
        $dialog.Close()
        $detail = if ($script:Language -eq 'zh-CN') {
            $script:SelectedGame.Name + '：智能全局模式 = ' + [string]$modeBox.SelectedItem
        } else {
            $script:SelectedGame.Name + ': auto global mode = ' + [string]$modeBox.SelectedItem
        }
        Set-Status (T 'ProfileSaved') $detail ([System.Drawing.Color]::FromArgb(67,190,120))
        $script:LastAdviceSummary = Get-GameAdvice $script:SelectedGame
        Update-AdvancedLabels
    })

    [void]$dialog.ShowDialog($form)
}

function Open-CustomTuningDialog {
    if (-not (Assert-GameBoostFeature 'customTuning' (T 'Tuning'))) { return }
    $dialog = New-Object System.Windows.Forms.Form
    $dialog.Text = if ($script:Language -eq 'zh-CN') { '电脑调校中心' } else { 'PC Tuning Center' }
    $dialog.Size = New-Object System.Drawing.Size(520,560)
    $dialog.StartPosition = 'CenterParent'
    $dialog.BackColor = [System.Drawing.Color]::FromArgb(18,24,32)
    $dialog.ForeColor = [System.Drawing.Color]::White
    $dialog.FormBorderStyle = 'FixedDialog'
    $dialog.MaximizeBox = $false
    $dialog.MinimizeBox = $false

    $title = New-Object System.Windows.Forms.Label
    $title.Text = if ($script:Language -eq 'zh-CN') { '全局电脑调校' } else { 'GLOBAL PC TUNING' }
    $title.Font = New-Object System.Drawing.Font('Microsoft YaHei UI',14,[System.Drawing.FontStyle]::Bold)
    $title.Location = New-Object System.Drawing.Point(22,18); $title.AutoSize = $true
    $dialog.Controls.Add($title)

    $hint = New-Object System.Windows.Forms.Label
    $hint.Text = if ($script:Language -eq 'zh-CN') { '设置写入独立 GameBoost 电源计划，可随时恢复启动前计划。' } else { 'Settings use a dedicated GameBoost power plan and can be restored.' }
    $hint.Location = New-Object System.Drawing.Point(24,48); $hint.Size = New-Object System.Drawing.Size(450,36)
    $hint.ForeColor = [System.Drawing.Color]::FromArgb(174,194,208)
    $dialog.Controls.Add($hint)

    $profileLabel = New-Object System.Windows.Forms.Label
    $profileLabel.Text = if ($script:Language -eq 'zh-CN') { '预设或已保存配置' } else { 'Preset or saved profile' }
    $profileLabel.Location = New-Object System.Drawing.Point(24,94); $profileLabel.AutoSize = $true
    $dialog.Controls.Add($profileLabel)

    $profileBox = New-Object System.Windows.Forms.ComboBox
    $profileBox.DropDownStyle = 'DropDownList'; $profileBox.Location = New-Object System.Drawing.Point(190,90); $profileBox.Size = New-Object System.Drawing.Size(280,28)
    [void]$profileBox.Items.AddRange(@('Balanced','High Performance','Competitive Low Latency','Quiet Saving'))
    $savedProfiles = Read-CustomTuningProfiles
    foreach ($name in ($savedProfiles.Keys | Sort-Object)) { [void]$profileBox.Items.Add(('Saved: ' + $name)) }
    $profileBox.SelectedIndex = 0
    $dialog.Controls.Add($profileBox)

    $nameLabel = New-Object System.Windows.Forms.Label
    $nameLabel.Text = if ($script:Language -eq 'zh-CN') { '保存名称' } else { 'Save name' }
    $nameLabel.Location = New-Object System.Drawing.Point(24,134); $nameLabel.AutoSize = $true
    $dialog.Controls.Add($nameLabel)

    $nameBox = New-Object System.Windows.Forms.TextBox
    $nameBox.Text = 'My Tuning'; $nameBox.Location = New-Object System.Drawing.Point(190,130); $nameBox.Size = New-Object System.Drawing.Size(280,28)
    $dialog.Controls.Add($nameBox)

    $cpuMinLabel = New-Object System.Windows.Forms.Label
    $cpuMinLabel.Text = if ($script:Language -eq 'zh-CN') { '插电 CPU 最低性能 (%)' } else { 'AC CPU minimum (%)' }
    $cpuMinLabel.Location = New-Object System.Drawing.Point(24,178); $cpuMinLabel.AutoSize = $true
    $dialog.Controls.Add($cpuMinLabel)

    $cpuMin = New-Object System.Windows.Forms.NumericUpDown
    $cpuMin.Minimum = 0; $cpuMin.Maximum = 100; $cpuMin.Location = New-Object System.Drawing.Point(350,174); $cpuMin.Size = New-Object System.Drawing.Size(120,28)
    $dialog.Controls.Add($cpuMin)

    $cpuMaxLabel = New-Object System.Windows.Forms.Label
    $cpuMaxLabel.Text = if ($script:Language -eq 'zh-CN') { '插电 CPU 最高性能 (%)' } else { 'AC CPU maximum (%)' }
    $cpuMaxLabel.Location = New-Object System.Drawing.Point(24,218); $cpuMaxLabel.AutoSize = $true
    $dialog.Controls.Add($cpuMaxLabel)

    $cpuMax = New-Object System.Windows.Forms.NumericUpDown
    $cpuMax.Minimum = 1; $cpuMax.Maximum = 100; $cpuMax.Location = New-Object System.Drawing.Point(350,214); $cpuMax.Size = New-Object System.Drawing.Size(120,28)
    $dialog.Controls.Add($cpuMax)

    $boostLabel = New-Object System.Windows.Forms.Label
    $boostLabel.Text = if ($script:Language -eq 'zh-CN') { 'CPU 加速策略 (0-4)' } else { 'CPU boost policy (0-4)' }
    $boostLabel.Location = New-Object System.Drawing.Point(24,258); $boostLabel.AutoSize = $true
    $dialog.Controls.Add($boostLabel)

    $boost = New-Object System.Windows.Forms.NumericUpDown
    $boost.Minimum = 0; $boost.Maximum = 4; $boost.Location = New-Object System.Drawing.Point(350,254); $boost.Size = New-Object System.Drawing.Size(120,28)
    $dialog.Controls.Add($boost)

    $pcie = New-Object System.Windows.Forms.CheckBox
    $pcie.Text = if ($script:Language -eq 'zh-CN') { '关闭 PCIe 链路节能' } else { 'Disable PCIe link saving' }
    $pcie.Location = New-Object System.Drawing.Point(24,302); $pcie.AutoSize = $true
    $dialog.Controls.Add($pcie)

    $wireless = New-Object System.Windows.Forms.CheckBox
    $wireless.Text = if ($script:Language -eq 'zh-CN') { '关闭无线网卡节能' } else { 'Disable wireless saving' }
    $wireless.Location = New-Object System.Drawing.Point(254,302); $wireless.AutoSize = $true
    $dialog.Controls.Add($wireless)

    $usb = New-Object System.Windows.Forms.CheckBox
    $usb.Text = if ($script:Language -eq 'zh-CN') { '关闭 USB 选择性暂停' } else { 'Disable USB selective suspend' }
    $usb.Location = New-Object System.Drawing.Point(24,338); $usb.AutoSize = $true
    $dialog.Controls.Add($usb)

    $awake = New-Object System.Windows.Forms.CheckBox
    $awake.Text = if ($script:Language -eq 'zh-CN') { '插电时不自动睡眠' } else { 'Keep awake while plugged in' }
    $awake.Location = New-Object System.Drawing.Point(254,338); $awake.AutoSize = $true
    $dialog.Controls.Add($awake)

    $setControls = {
        param($settings)
        $nameBox.Text = [string]$settings.Name
        $cpuMin.Value = [decimal][int]$settings.CpuMinAc; $cpuMax.Value = [decimal][int]$settings.CpuMaxAc; $boost.Value = [decimal][int]$settings.CpuBoostAc
        $pcie.Checked = [bool]$settings.DisablePcieSaving; $wireless.Checked = [bool]$settings.DisableWirelessSaving; $usb.Checked = [bool]$settings.DisableUsbSuspend; $awake.Checked = [bool]$settings.KeepAwake
    }
    & $setControls (Get-CustomTuningPreset 'Balanced')

    $profileBox.Add_SelectedIndexChanged({
        $selected = [string]$profileBox.SelectedItem
        if ($selected -like 'Saved: *') {
            $key = $selected.Substring(7)
            if ($savedProfiles.ContainsKey($key)) { & $setControls $savedProfiles[$key] }
        } else { & $setControls (Get-CustomTuningPreset $selected) }
    })

    $getSettings = {
        [pscustomobject]@{
            Name = if ($nameBox.Text.Trim()) { $nameBox.Text.Trim() } else { 'My Tuning' }
            CpuMinAc = [int]$cpuMin.Value; CpuMaxAc = [int]$cpuMax.Value; CpuBoostAc = [int]$boost.Value
            CpuMinDc = 5; CpuMaxDc = 75; CpuBoostDc = 3
            DisablePcieSaving = $pcie.Checked; DisableWirelessSaving = $wireless.Checked; DisableUsbSuspend = $usb.Checked; KeepAwake = $awake.Checked
        }
    }

    $save = New-Object System.Windows.Forms.Button
    $save.Text = if ($script:Language -eq 'zh-CN') { '保存配置' } else { 'SAVE PROFILE' }
    $save.Location = New-Object System.Drawing.Point(24,412); $save.Size = New-Object System.Drawing.Size(130,38)
    $save.FlatStyle = 'Flat'; $save.BackColor = [System.Drawing.Color]::FromArgb(80,90,105); $save.ForeColor = [System.Drawing.Color]::White
    $dialog.Controls.Add($save)
    $save.Add_Click({
        $settings = & $getSettings
        $profiles = Read-CustomTuningProfiles; $profiles[$settings.Name] = $settings; Save-CustomTuningProfiles $profiles
        Set-Status (T 'Tuning') ((if ($script:Language -eq 'zh-CN') { '已保存全局配置：' } else { 'Saved global profile: ' }) + $settings.Name) ([System.Drawing.Color]::FromArgb(67,190,120))
    })

    $restore = New-Object System.Windows.Forms.Button
    $restore.Text = if ($script:Language -eq 'zh-CN') { '恢复启动前计划' } else { 'RESTORE STARTUP PLAN' }
    $restore.Location = New-Object System.Drawing.Point(162,412); $restore.Size = New-Object System.Drawing.Size(160,38)
    $restore.FlatStyle = 'Flat'; $restore.BackColor = [System.Drawing.Color]::FromArgb(50,55,64); $restore.ForeColor = [System.Drawing.Color]::White
    $dialog.Controls.Add($restore)
    $restore.Add_Click({ Restore-GameBoostNormal; $dialog.Close() })

    $apply = New-Object System.Windows.Forms.Button
    $apply.Text = if ($script:Language -eq 'zh-CN') { '应用到电脑' } else { 'APPLY TO PC' }
    $apply.Location = New-Object System.Drawing.Point(330,412); $apply.Size = New-Object System.Drawing.Size(140,38)
    $apply.FlatStyle = 'Flat'; $apply.BackColor = [System.Drawing.Color]::FromArgb(46,115,210); $apply.ForeColor = [System.Drawing.Color]::White
    $dialog.Controls.Add($apply)
    $apply.Add_Click({
        $result = Apply-CustomTuningSettings (& $getSettings)
        $color = if ($result.Success) { [System.Drawing.Color]::FromArgb(67,190,120) } else { [System.Drawing.Color]::FromArgb(205,80,55) }
        Set-Status (T 'Tuning') $result.Message $color
        if ($result.Success) { $dialog.Close() }
    })

    [void]$dialog.ShowDialog($form)
}

function Toggle-ThermalGuard {
    if (-not (Assert-GameBoostFeature 'thermalGuard' (T 'Thermal'))) { return }
    $script:ThermalGuardEnabled = -not $script:ThermalGuardEnabled
    Set-ThermalButtonState
    $detail = if ($script:ThermalGuardEnabled) {
        'Thermal guard enabled at ' + $script:ThermalLimitC + ' C.'
    } else {
        'Thermal guard disabled.'
    }
    Set-Status (T 'Thermal') $detail ([System.Drawing.Color]::FromArgb(220,160,40))
    Update-AdvancedLabels
}

function Invoke-ThermalGuard {
    param($Gpu)
    if (-not (Test-GameBoostFeature 'thermalGuard')) { return }
    if (-not $script:ThermalGuardEnabled -or -not $Gpu) { return }
    $temp = 0
    if (-not [int]::TryParse([string]$Gpu.Temp, [ref]$temp)) { return }

    $running = Get-PrimaryRunningGame
    $limit = Get-CompetitiveThermalLimit $(if ($running) { $running.Game } else { $script:SelectedGame })
    if ($script:ExtremeModeActive -and $temp -ge $limit) {
        $script:ThermalThrottleUntil = (Get-Date).AddMinutes(2)
        if ($running) { Update-GameLearningProfile -Game $running.Game -Event 'ThermalDownshift' -Gpu $Gpu }
        $detail = if ($script:Language -eq 'zh-CN') {
            'GPU 已到 ' + $temp + ' C（阈值 ' + $limit + ' C），已临时退出最佳优化，防止过热降频。'
        } else {
            'GPU reached ' + $temp + ' C; extreme mode paused to avoid thermal throttling.'
        }
        Restore-GameBoostNormal -KeepSmartGlobal -Title (T 'ThermalDownshift') -Detail $detail
    }
}

function Get-SteamLibraries {
    $roots = New-Object System.Collections.ArrayList
    $steamPath = (Get-ItemProperty 'HKCU:\Software\Valve\Steam' -ErrorAction SilentlyContinue).SteamPath
    if ($steamPath) { [void]$roots.Add(($steamPath -replace '/', '\')) }
    foreach ($candidate in @('C:\Program Files (x86)\Steam', 'C:\Program Files\Steam', 'D:\SteamLibrary', 'E:\SteamLibrary', 'F:\SteamLibrary')) {
        if (Test-Path $candidate) { [void]$roots.Add($candidate) }
    }
    $libraryFiles = @($roots | ForEach-Object { Join-Path $_ 'steamapps\libraryfolders.vdf' } | Where-Object { Test-Path $_ })
    foreach ($file in $libraryFiles) {
        $content = Get-Content -LiteralPath $file -Raw -ErrorAction SilentlyContinue
        [regex]::Matches($content, '"path"\s+"([^"]+)"') | ForEach-Object {
            $path = $_.Groups[1].Value -replace '\\\\', '\'
            if (Test-Path $path) { [void]$roots.Add($path) }
        }
    }
    $seen = @{}
    return @($roots | ForEach-Object {
        $full = [IO.Path]::GetFullPath($_).TrimEnd('\')
        $key = $full.ToLowerInvariant()
        if (-not $seen.ContainsKey($key)) { $seen[$key] = $true; $full }
    })
}

function Find-GameExecutable {
    param([string]$InstallPath, [string]$Name)
    if (-not (Test-Path $InstallPath)) { return $null }
    if ($Name -match 'PUBG') {
        $pubg = Join-Path $InstallPath 'TslGame\Binaries\Win64\TslGame.exe'
        if (Test-Path $pubg) { return $pubg }
    }
    if ($Name -eq 'War Thunder') {
        $warThunder = Join-Path $InstallPath 'win64\aces.exe'
        if (Test-Path $warThunder) { return $warThunder }
    }
    $exclude = 'crash|report|unins|setup|redist|launcher|service|helper|benchmark|cef|update|diagnostic|overlay|download'
    $normalizedName = ($Name -replace '[^a-zA-Z0-9]', '').ToLowerInvariant()
    $candidates = @(Get-ChildItem -LiteralPath $InstallPath -Filter '*.exe' -File -Recurse -ErrorAction SilentlyContinue |
        Where-Object { $_.Name -notmatch $exclude -and $_.FullName -notmatch '\\(_CommonRedist|Engine\\Binaries\\ThirdParty|EasyAntiCheat|BattlEye)\\' }
    )
    if ($candidates.Count -eq 0) { return $null }
    return $candidates | ForEach-Object {
        $base = ($_.BaseName -replace '[^a-zA-Z0-9]', '').ToLowerInvariant()
        $score = 0
        if ($base -eq $normalizedName) { $score += 1000 }
        elseif ($normalizedName.Contains($base) -or $base.Contains($normalizedName)) { $score += 500 }
        if ($_.FullName -match '\\Binaries\\Win64\\') { $score += 220 }
        elseif ($_.DirectoryName -eq $InstallPath) { $score += 180 }
        if ($_.Name -match '(game|client|win64|shipping)') { $score += 80 }
        $score += [Math]::Min([int]($_.Length / 1MB), 150)
        [pscustomobject]@{ Path=$_.FullName; Score=$score; Size=$_.Length }
    } | Sort-Object Score,Size -Descending | Select-Object -First 1 -ExpandProperty Path
}

function Get-SteamGames {
    foreach ($root in Get-SteamLibraries) {
        $steamApps = Join-Path $root 'steamapps'
        Get-ChildItem -LiteralPath $steamApps -Filter 'appmanifest_*.acf' -File -ErrorAction SilentlyContinue | ForEach-Object {
            $text = Get-Content -LiteralPath $_.FullName -Raw -ErrorAction SilentlyContinue
            $appId = if ($text -match '"appid"\s+"(\d+)"') { $matches[1] } else { $null }
            $name = if ($text -match '"name"\s+"([^"]+)"') { $matches[1] } else { $null }
            $installDir = if ($text -match '"installdir"\s+"([^"]+)"') { $matches[1] } else { $null }
            if ($appId -and $name -and $installDir -and $appId -ne '228980') {
                $installPath = Join-Path (Join-Path $steamApps 'common') $installDir
                $exe = Find-GameExecutable -InstallPath $installPath -Name $name
                [pscustomobject]@{ Name=$name; Source='Steam'; AppId=$appId; Exe=$exe; InstallPath=$installPath; Optimized=[bool]$exe }
            }
        }
    }
}

function Set-HighPerformanceGpu {
    param([string]$Exe)
    if (-not $Exe) { return $false }
    try {
        $path = 'HKCU:\Software\Microsoft\DirectX\UserGpuPreferences'
        New-Item -Path $path -Force -ErrorAction Stop | Out-Null
        New-ItemProperty -Path $path -Name $Exe -PropertyType String -Value 'GpuPreference=2;' -Force -ErrorAction Stop | Out-Null
        return $true
    } catch {
        return $false
    }
}

function Get-GameStatusText {
    param($Game)
    if ($Game.Exe) { return 'Optimized' }
    if ($Game.Source -eq 'Steam' -and $Game.AppId) { return 'Steam Launch' }
    return 'Select EXE'
}

function Get-LaunchableGameCount {
    param([object[]]$Games)
    return @($Games | Where-Object { $_.Exe -or ($_.Source -eq 'Steam' -and $_.AppId) }).Count
}

function Read-CustomTuningProfiles {
    if (-not (Test-Path -LiteralPath $script:TuningFile)) { return @{} }
    try {
        $json = Get-Content -LiteralPath $script:TuningFile -Raw -Encoding UTF8 | ConvertFrom-Json
        $profiles = @{}
        foreach ($property in $json.PSObject.Properties) { $profiles[$property.Name] = $property.Value }
        return $profiles
    } catch { return @{} }
}

function Save-CustomTuningProfiles {
    param([hashtable]$Profiles)
    try { $Profiles | ConvertTo-Json -Depth 4 | Set-Content -LiteralPath $script:TuningFile -Encoding UTF8 } catch {}
}

function Get-CustomTuningPreset {
    param([string]$Name)
    $preset = if ($Name) { $Name } else { 'Balanced' }
    $values = [ordered]@{
        Name = $preset
        CpuMinAc = 5; CpuMaxAc = 100; CpuBoostAc = 3
        CpuMinDc = 5; CpuMaxDc = 75; CpuBoostDc = 3
        DisablePcieSaving = $true; DisableWirelessSaving = $true; DisableUsbSuspend = $true
        KeepAwake = $false
    }
    if ($preset -eq 'High Performance') {
        $values.CpuMinAc = 50; $values.CpuBoostAc = 4; $values.CpuMaxDc = 85
    } elseif ($preset -eq 'Competitive Low Latency') {
        $values.CpuMinAc = 85; $values.CpuBoostAc = 4; $values.KeepAwake = $true
    } elseif ($preset -eq 'Quiet Saving') {
        $values.CpuMinAc = 5; $values.CpuMaxAc = 85; $values.CpuBoostAc = 0
        $values.CpuMaxDc = 65; $values.DisablePcieSaving = $false; $values.DisableWirelessSaving = $false; $values.DisableUsbSuspend = $false
    }
    return [pscustomobject]$values
}

function New-CustomTuningPlan {
    param($Settings)
    return [pscustomobject]@{
        SchemeName = $script:CustomTuningSchemeName
        Description = 'Customer controlled Windows power tuning'
        Mode = 'Custom Tuning'
        CpuMinAc = [int]$Settings.CpuMinAc; CpuMaxAc = [int]$Settings.CpuMaxAc; CpuBoostAc = [int]$Settings.CpuBoostAc
        CpuMinDc = [int]$Settings.CpuMinDc; CpuMaxDc = [int]$Settings.CpuMaxDc; CpuBoostDc = [int]$Settings.CpuBoostDc
        CoolingPolicy = 1
        PcieLinkState = if ($Settings.DisablePcieSaving) { 0 } else { 1 }
        WirelessSaving = if ($Settings.DisableWirelessSaving) { 0 } else { 2 }
        UsbSelectiveSuspend = if ($Settings.DisableUsbSuspend) { 0 } else { 1 }
        DisableIdleSleep = [bool]$Settings.KeepAwake
        DiskIdleAc = if ($Settings.KeepAwake) { 0 } else { 20 }
        DiskIdleDc = if ($Settings.KeepAwake) { 0 } else { 10 }
        SleepAfterAc = if ($Settings.KeepAwake) { 0 } else { 30 }
        SleepAfterDc = if ($Settings.KeepAwake) { 0 } else { 15 }
        HibernateAfterAc = if ($Settings.KeepAwake) { 0 } else { 120 }
        HibernateAfterDc = if ($Settings.KeepAwake) { 0 } else { 60 }
        CloseBackground = $false
        Summary = 'Custom Windows tuning: ' + [string]$Settings.Name
        Notes = @('Stored in a dedicated GameBoost power plan and can be restored.')
    }
}

function Apply-CustomTuningSettings {
    param($Settings)
    if (-not $script:FallbackScheme) { $script:FallbackScheme = Get-ActiveScheme }
    if ([int]$Settings.CpuMinAc -gt [int]$Settings.CpuMaxAc) { return [pscustomobject]@{ Success=$false; Message='CPU minimum cannot exceed CPU maximum.' } }
    $plan = New-CustomTuningPlan $Settings
    $scheme = Ensure-GameBoostPowerScheme -Plan $plan
    $result = Invoke-PowerCfg @('/setactive', $scheme)
    if ($result.ExitCode -ne 0) { return [pscustomobject]@{ Success=$false; Message='Windows rejected the custom power profile.' } }
    $script:ExtremeModeActive = $false
    return [pscustomobject]@{ Success=$true; Message='Custom tuning is active: ' + $Settings.Name; Scheme=$scheme }
}

function New-GameBoostSelfTestResult {
    param([string]$Name, [string]$Status, [string]$Detail)
    [pscustomobject][ordered]@{ Name=$Name; Status=$Status; Detail=$Detail }
}

function Invoke-GameBoostSelfTest {
    $results = New-Object System.Collections.ArrayList
    $add = {
        param([string]$Name, [string]$Status, [string]$Detail)
        [void]$results.Add((New-GameBoostSelfTestResult -Name $Name -Status $Status -Detail $Detail))
    }

    try {
        $parseErrors = $null
        [void][System.Management.Automation.Language.Parser]::ParseFile($PSCommandPath, [ref]$null, [ref]$parseErrors)
        if ($parseErrors.Count -eq 0) { & $add 'ScriptSyntax' 'Pass' 'PowerShell AST parsed successfully.' }
        else { & $add 'ScriptSyntax' 'Fail' $parseErrors[0].Message }
    } catch { & $add 'ScriptSyntax' 'Fail' $_.Exception.Message }

    $requiredCommands = @('powercfg.exe','nvidia-smi','ipconfig.exe','netsh.exe')
    $missingCommands = @($requiredCommands | Where-Object { -not (Get-Command $_ -ErrorAction SilentlyContinue) })
    if ($missingCommands.Count -eq 0) { & $add 'SystemDependencies' 'Pass' 'Power, GPU and network command dependencies are available.' }
    else { & $add 'SystemDependencies' 'Fail' ('Missing commands: ' + ($missingCommands -join ', ')) }

    $planFields = @('Mode','CpuMinAc','CpuMaxAc','CpuBoostAc','Summary')
    $missingPlanFields = @($planFields | Where-Object { $script:AdaptivePlan.PSObject.Properties.Name -notcontains $_ })
    if ($script:SystemProfile -and $script:AdaptivePlan -and $script:ExtremePlan -and $missingPlanFields.Count -eq 0) {
        & $add 'HardwarePlanning' 'Pass' ('Adaptive=' + $script:AdaptivePlan.Mode + '; Extreme=' + $script:ExtremePlan.Mode)
    } else { & $add 'HardwarePlanning' 'Fail' 'Hardware profile or optimization plans are incomplete.' }

    $knownSchemes = @(Get-PowerSchemes | Where-Object { $_.Guid -eq $script:OptimizedScheme })
    if ($script:PowerSchemeReady -and $script:OptimizedScheme -and $knownSchemes.Count -eq 1) {
        & $add 'PowerProfile' 'Pass' ($script:PowerSchemeName + ' is registered: ' + $script:OptimizedScheme)
    } else { & $add 'PowerProfile' 'Fail' $script:PowerSchemeMessage }

    $gameSettingsReady = Set-WindowsGameSettings -Extreme
    $gameStore = Get-ItemProperty -Path 'HKCU:\System\GameConfigStore' -ErrorAction SilentlyContinue
    $gameBar = Get-ItemProperty -Path 'HKCU:\Software\Microsoft\GameBar' -ErrorAction SilentlyContinue
    if ($gameSettingsReady -and $gameStore.GameDVR_Enabled -eq 0 -and $gameBar.AutoGameModeEnabled -eq 1) {
        & $add 'WindowsGameSettings' 'Pass' 'Game DVR disabled and Auto Game Mode enabled for the current user.'
    } else { & $add 'WindowsGameSettings' 'Fail' 'Required HKCU game settings could not be verified.' }

    try {
        $timerStarted = Enable-LowLatencyTimer
        Disable-LowLatencyTimer
        if ($timerStarted -and -not $script:TimerResolutionActive) { & $add 'LowLatencyTimer' 'Pass' '1 ms timer request can start and cleanly release.' }
        else { & $add 'LowLatencyTimer' 'Fail' 'Timer request did not return to its inactive state.' }
    } catch { & $add 'LowLatencyTimer' 'Fail' $_.Exception.Message }

    $games = @(Get-SteamGames | Sort-Object Name -Unique)
    $launchable = Get-LaunchableGameCount $games
    if ($games.Count -gt 0 -and $launchable -gt 0) { & $add 'SteamDiscovery' 'Pass' ($games.Count.ToString() + ' games found; ' + $launchable.ToString() + ' launchable.') }
    elseif ($games.Count -eq 0) { & $add 'SteamDiscovery' 'Skip' 'No Steam library was found on this PC.' }
    else { & $add 'SteamDiscovery' 'Fail' 'Games were found but none can be launched.' }

    try {
        $tuning = Get-CustomTuningPreset 'Competitive Low Latency'
        $tuningPlan = New-CustomTuningPlan $tuning
        if ($tuningPlan.SchemeName -eq $script:CustomTuningSchemeName -and $tuningPlan.CpuMinAc -le $tuningPlan.CpuMaxAc -and $tuningPlan.PcieLinkState -eq 0) {
            & $add 'CustomTuning' 'Pass' 'Global tuning presets and the dedicated power plan model are valid.'
        } else { & $add 'CustomTuning' 'Fail' 'Custom tuning preset values are invalid.' }
    } catch { & $add 'CustomTuning' 'Fail' $_.Exception.Message }

    try {
        $freeFeatures = Get-GameBoostFeatureSet 'free'
        $proFeatures = Get-GameBoostFeatureSet 'pro'
        $trialFeatures = Get-GameBoostFeatureSet 'trial'
        if (-not $freeFeatures.extremeOptimization -and $proFeatures.extremeOptimization -and $trialFeatures.extremeOptimization) {
            & $add 'LicenseFeatureGate' 'Pass' 'Free blocks Pro-only features; Pro and trial unlock them.'
        } else {
            & $add 'LicenseFeatureGate' 'Fail' 'License feature matrix is inconsistent.'
        }
    } catch { & $add 'LicenseFeatureGate' 'Fail' $_.Exception.Message }

    try {
        $hostProcess = Get-CimInstance Win32_Process -Filter ('ProcessId = ' + $PID) -ErrorAction Stop
        if ($hostProcess.ExecutablePath) {
            $hostGame = [pscustomobject]@{ Name='GameBoost SelfTest Host'; Source='SelfTest'; AppId='0'; Exe=$null; InstallPath=(Split-Path -Parent $hostProcess.ExecutablePath) }
            $hostMatch = @(Get-RunningGameProcesses @($hostGame) | Where-Object { $_.ProcessId -eq $PID })
            if ($hostMatch.Count -eq 1) { & $add 'SmartGlobalDetection' 'Pass' 'Installation-directory process matching detected the current test process.' }
            else { & $add 'SmartGlobalDetection' 'Fail' 'Installation-directory process matching did not detect the current test process.' }
        } else { & $add 'SmartGlobalDetection' 'Skip' 'This PowerShell host does not expose ExecutablePath through CIM.' }
    } catch { & $add 'SmartGlobalDetection' 'Fail' $_.Exception.Message }

    try {
        Ensure-MetricsFolder
        $probeFile = Join-Path $script:MetricsFolder ('selftest-' + [guid]::NewGuid().ToString('N') + '.tmp')
        'GameBoost self-test' | Set-Content -LiteralPath $probeFile -Encoding UTF8 -ErrorAction Stop
        $isWritable = (Get-Content -LiteralPath $probeFile -Raw -ErrorAction Stop) -match 'GameBoost self-test'
        Remove-Item -LiteralPath $probeFile -Force -ErrorAction Stop
        if ($isWritable) { & $add 'MetricsStorage' 'Pass' ('Metrics folder is writable: ' + $script:MetricsFolder) }
        else { & $add 'MetricsStorage' 'Fail' 'Metrics probe file could not be read back.' }
    } catch { & $add 'MetricsStorage' 'Fail' $_.Exception.Message }

    try {
        $sampleGame = [pscustomobject]@{ Name='GameBoost SelfTest'; Source='SelfTest'; AppId='0'; Exe=''; InstallPath='' }
        $profile = Ensure-GameLearningProfileShape -Game $sampleGame -Profile ([pscustomobject]@{ Name='GameBoost SelfTest' })
        $advice = Get-GameAdvice $sampleGame
        if ($profile.PreferredMode -eq 'Auto' -and $advice.Count -gt 0) { & $add 'GameProfiles' 'Pass' 'Learning-profile normalization and advice generation are available.' }
        else { & $add 'GameProfiles' 'Fail' 'Profile normalization or advice generation returned incomplete data.' }
    } catch { & $add 'GameProfiles' 'Fail' $_.Exception.Message }

    $networkTools = @('ipconfig.exe','netsh.exe') | Where-Object { Get-Command $_ -ErrorAction SilentlyContinue }
    if ($networkTools.Count -eq 2) { & $add 'NetworkOptimization' 'Pass' 'Network optimization dependencies are available; policy changes were not applied during self-test.' }
    else { & $add 'NetworkOptimization' 'Fail' 'ipconfig.exe or netsh.exe is unavailable.' }

    if (Test-GameBoostAdministrator) {
        & $add 'ExtremeSystemPolicy' 'Skip' 'Administrator detected; skipped HKLM policy write to keep self-test non-invasive.'
    } else {
        $previousErrors = $Error.Count
        $policyResult = Set-ExtremeSystemGamePolicy
        if (-not $policyResult -and $Error.Count -eq $previousErrors) { & $add 'ExtremeSystemPolicy' 'Skip' 'Administrator rights are required; non-admin fallback completed without registry errors.' }
        else { & $add 'ExtremeSystemPolicy' 'Fail' 'Non-admin fallback produced an unexpected result.' }
    }

    $source = Get-Content -LiteralPath $PSCommandPath -Raw -Encoding UTF8
    $expectedHandlers = @('Refresh-GameList','Launch-SelectedGame','Optimize-AllGames','Optimize-ExtremeAllGames','Toggle-SmartGlobal','Toggle-MetricsLogging','Show-MetricsChart','Update-AutoMetricsSession','Get-NetworkLatencyMs','Invoke-NetworkGameOptimization','Toggle-ThermalGuard','Show-CompetitivePreflight','Open-GameProfileDialog','Open-CustomTuningDialog','Restore-GameBoostNormal')
    $missingHandlers = @($expectedHandlers | Where-Object { $source -notmatch [regex]::Escape($_) })
    if ($missingHandlers.Count -eq 0) { & $add 'UiBindings' 'Pass' 'All primary UI action handlers are present in the script.' }
    else { & $add 'UiBindings' 'Fail' ('Missing handlers: ' + ($missingHandlers -join ', ')) }

    [pscustomobject][ordered]@{
        TestedAt = (Get-Date).ToString('s')
        Passed = @($results | Where-Object Status -eq 'Pass').Count
        Failed = @($results | Where-Object Status -eq 'Fail').Count
        Skipped = @($results | Where-Object Status -eq 'Skip').Count
        Results = @($results)
    }
}

function Get-SmartGlobalDiagnostics {
    $games = @(Get-SteamGames | Sort-Object Name -Unique)
    $candidateGames = @($games | Where-Object { Test-SmartGlobalGameCandidate $_ })
    $processes = @(Get-CimInstance Win32_Process -ErrorAction SilentlyContinue)
    $matches = @(Get-RunningGameProcesses $games)
    [pscustomobject][ordered]@{
        CheckedAt = (Get-Date).ToString('s')
        ScannedGameCount = $games.Count
        EligibleGameCount = $candidateGames.Count
        VisibleProcessCount = $processes.Count
        Games = @($candidateGames | ForEach-Object {
            [pscustomobject]@{ Name=$_.Name; AppId=$_.AppId; Exe=$_.Exe; InstallPath=$_.InstallPath }
        })
        Matches = @($matches | ForEach-Object {
            [pscustomobject]@{ Game=$_.Game.Name; ProcessId=$_.ProcessId; ProcessName=$_.ProcessName; ExecutablePath=$_.ExecutablePath }
        })
    }
}

$script:SystemProfile = Get-SystemProfile
$script:AdaptivePlan = Get-AdaptivePlan -Profile $script:SystemProfile
$script:ExtremePlan = Get-ExtremePlan -Profile $script:SystemProfile
$script:FallbackScheme = Get-ActiveScheme
$script:OptimizedScheme = Ensure-GameBoostPowerScheme -Plan $script:AdaptivePlan
$script:LicenseState = Invoke-GameBoostLicenseVerification
if (-not (Test-GameBoostFeature 'thermalGuard')) { $script:ThermalGuardEnabled = $false }

if ($WinUiAction) {
    switch ($WinUiAction) {
        'Scan' {
            $games = @(Get-SteamGames | Sort-Object Name -Unique)
            [pscustomobject][ordered]@{
                Action = 'Scan'; CompletedAt = (Get-Date).ToString('s'); Hardware = $script:SystemProfile
                ActiveScheme = (Get-ActiveScheme); Games = @($games | ForEach-Object {
                    [pscustomobject]@{ Name=$_.Name; Source=$_.Source; AppId=$_.AppId; Status=(Get-GameStatusText $_); Exe=$_.Exe; InstallPath=$_.InstallPath }
                })
            } | ConvertTo-Json -Depth 5
        }
        'Normal' {
            $games = @(Get-SteamGames | Sort-Object Name -Unique)
            if (-not (Test-Path -LiteralPath $script:WinUiRestoreFile)) { @{ Scheme=(Get-ActiveScheme); SavedAt=(Get-Date).ToString('s') } | ConvertTo-Json | Set-Content -LiteralPath $script:WinUiRestoreFile -Encoding UTF8 }
            $powerReady = Set-GameBoostPowerActive
            Disable-LowLatencyTimer
            [void](Set-WindowsGameSettings)
            $gpuCount = 0
            foreach ($game in $games) { if ($game.Exe -and (Set-HighPerformanceGpu $game.Exe)) { $gpuCount++ } }
            [pscustomobject][ordered]@{ Action='Normal'; CompletedAt=(Get-Date).ToString('s'); Allowed=$true; Message=($gpuCount.ToString() + ' GPU profiles prepared; normal power mode is active.'); Result=[pscustomobject]@{ PowerReady=$powerReady; GpuCount=$gpuCount; LaunchableCount=@($games | Where-Object { $_.Exe -or ($_.Source -eq 'Steam' -and $_.AppId) }).Count }; ActiveScheme=(Get-ActiveScheme) } | ConvertTo-Json -Depth 5
        }
        'Extreme' {
            if (-not (Test-GameBoostFeature 'extremeOptimization')) {
                [pscustomobject][ordered]@{ Action='Extreme'; CompletedAt=(Get-Date).ToString('s'); Allowed=$false; Message='Professional license is required for Extreme optimization.' } | ConvertTo-Json -Depth 4
            } else {
                $games = @(Get-SteamGames | Sort-Object Name -Unique)
                if (-not (Test-Path -LiteralPath $script:WinUiRestoreFile)) { @{ Scheme=(Get-ActiveScheme); SavedAt=(Get-Date).ToString('s') } | ConvertTo-Json | Set-Content -LiteralPath $script:WinUiRestoreFile -Encoding UTF8 }
                $script:SystemProfile = Get-SystemProfile
                $script:ExtremePlan = Get-ExtremePlan -Profile $script:SystemProfile
                $script:ExtremeScheme = Ensure-GameBoostPowerScheme -Plan $script:ExtremePlan
                $powerReady = Set-GameBoostPowerActive -Extreme
                [void](Set-WindowsGameSettings -Extreme)
                $systemPolicyReady = Set-ExtremeSystemGamePolicy
                $timerReady = Enable-LowLatencyTimer
                $gpuCount = 0
                foreach ($game in $games) { if ($game.Exe -and (Set-HighPerformanceGpu $game.Exe)) { $gpuCount++ } }
                [pscustomobject][ordered]@{ Action='Extreme'; CompletedAt=(Get-Date).ToString('s'); Allowed=$true; Message=($gpuCount.ToString() + ' GPU profiles prepared; extreme power mode is active.'); Result=[pscustomobject]@{ PowerReady=$powerReady; GpuCount=$gpuCount; SystemPolicyReady=$systemPolicyReady; TimerReady=$timerReady }; ActiveScheme=(Get-ActiveScheme) } | ConvertTo-Json -Depth 5
            }
        }
        'Restore' {
            Disable-LowLatencyTimer
            $script:ExtremeModeActive = $false
            $restoreScheme = $script:FallbackScheme
            try { if (Test-Path -LiteralPath $script:WinUiRestoreFile) { $saved = Get-Content -LiteralPath $script:WinUiRestoreFile -Raw -Encoding UTF8 | ConvertFrom-Json; if ($saved.Scheme) { $restoreScheme = [string]$saved.Scheme } } } catch {}
            if ($restoreScheme) { [void](Invoke-PowerCfg @('/setactive', $restoreScheme)) }
            if (Test-Path -LiteralPath $script:WinUiRestoreFile) { Remove-Item -LiteralPath $script:WinUiRestoreFile -Force -ErrorAction SilentlyContinue }
            [pscustomobject][ordered]@{ Action='Restore'; CompletedAt=(Get-Date).ToString('s'); RestoredScheme=$restoreScheme; ActiveScheme=(Get-ActiveScheme) } | ConvertTo-Json -Depth 4
        }
        'LicenseStatus' {
            [pscustomobject][ordered]@{ Action='LicenseStatus'; CompletedAt=(Get-Date).ToString('s'); License=$script:LicenseState; Features=(Get-GameBoostFeatureSet $script:LicenseState.Plan) } | ConvertTo-Json -Depth 5
        }
        'Telemetry' {
            $gpu = Get-GpuStatus
            $pingMs = $null
            try { $reply = (New-Object System.Net.NetworkInformation.Ping).Send('1.1.1.1',700); if ($reply.Status -eq 'Success') { $pingMs = [int]$reply.RoundtripTime } } catch {}
            [pscustomobject][ordered]@{ Action='Telemetry'; SampledAt=(Get-Date).ToString('s'); Gpu=$gpu; PingMs=$pingMs; ActiveScheme=(Get-ActiveScheme); ThermalLimitC=$script:ThermalLimitC } | ConvertTo-Json -Depth 4
        }
        'NetworkProbe' {
            $targets = @('223.5.5.5','114.114.114.114','1.1.1.1')
            $rows = foreach ($target in $targets) {
                try { $reply = (New-Object System.Net.NetworkInformation.Ping).Send($target,800); [pscustomobject]@{ Target=$target; Success=($reply.Status -eq 'Success'); PingMs=if($reply.Status -eq 'Success'){[int]$reply.RoundtripTime}else{$null} } }
                catch { [pscustomobject]@{ Target=$target; Success=$false; PingMs=$null } }
            }
            [pscustomobject][ordered]@{ Action='NetworkProbe'; CompletedAt=(Get-Date).ToString('s'); Allowed=$true; Rows=@($rows) } | ConvertTo-Json -Depth 4
        }
        'RunningGames' {
            $games = @(Get-SteamGames | Sort-Object Name -Unique)
            $matches = @(Get-RunningGameProcesses $games)
            [pscustomobject][ordered]@{ Action='RunningGames'; CheckedAt=(Get-Date).ToString('s'); Matches=@($matches | ForEach-Object { [pscustomobject]@{ Name=$_.Game.Name; ProcessId=$_.ProcessId; ProcessName=$_.ProcessName; ExecutablePath=$_.ExecutablePath } }) } | ConvertTo-Json -Depth 4
        }
        'GetProfile' {
            $key = $WinUiGameName.ToLowerInvariant()
            $mode = 'Auto'
            try { if (Test-Path -LiteralPath $script:LearningFile) { $profiles = Get-Content -LiteralPath $script:LearningFile -Raw -Encoding UTF8 | ConvertFrom-Json; $entry = $profiles.PSObject.Properties[$key]; if ($entry -and $entry.Value.PreferredMode) { $mode = [string]$entry.Value.PreferredMode } } } catch {}
            [pscustomobject]@{ Action='GetProfile'; Allowed=$true; Game=$WinUiGameName; PreferredMode=$mode } | ConvertTo-Json
        }
        'SetProfile' {
            if (-not $WinUiGameName) { [pscustomobject]@{ Action='SetProfile'; Allowed=$false; Message='Select a game first.' } | ConvertTo-Json; break }
            $profiles = @{}
            try { if (Test-Path -LiteralPath $script:LearningFile) { $raw = Get-Content -LiteralPath $script:LearningFile -Raw -Encoding UTF8 | ConvertFrom-Json; foreach ($property in $raw.PSObject.Properties) { $profiles[$property.Name] = $property.Value } } } catch {}
            $key = $WinUiGameName.ToLowerInvariant()
            if (-not $profiles.ContainsKey($key)) { $profiles[$key] = [pscustomobject]@{ Name=$WinUiGameName; AppId=''; PreferredMode='Auto'; NetworkOptimized=$false; Sessions=0; ExtremeSessions=0; NormalSessions=0; ThermalDownshifts=0; LastMode=''; LastGpuTempC=''; LastSeen='' } }
            $profiles[$key].PreferredMode = $WinUiProfileMode
            $profiles | ConvertTo-Json -Depth 5 | Set-Content -LiteralPath $script:LearningFile -Encoding UTF8
            [pscustomobject]@{ Action='SetProfile'; Allowed=$true; Message=($WinUiGameName + ' profile saved as ' + $WinUiProfileMode + '.'); PreferredMode=$WinUiProfileMode } | ConvertTo-Json
        }
        'ApplyTuning' {
            $settings = [ordered]@{ Name=$WinUiTuningPreset; CpuMinAc=5; CpuMaxAc=100; CpuBoostAc=3; CpuMinDc=5; CpuMaxDc=75; CpuBoostDc=3; DisablePcieSaving=$true; DisableWirelessSaving=$true; DisableUsbSuspend=$true; KeepAwake=$false }
            if ($WinUiTuningPreset -eq 'High Performance') { $settings.CpuMinAc=50; $settings.CpuBoostAc=4; $settings.CpuMaxDc=85 }
            elseif ($WinUiTuningPreset -eq 'Competitive Low Latency') { $settings.CpuMinAc=85; $settings.CpuBoostAc=4; $settings.KeepAwake=$true }
            elseif ($WinUiTuningPreset -eq 'Quiet Saving') { $settings.CpuMaxAc=85; $settings.CpuBoostAc=0; $settings.CpuMaxDc=65; $settings.DisablePcieSaving=$false; $settings.DisableWirelessSaving=$false; $settings.DisableUsbSuspend=$false }
            if (-not $script:FallbackScheme) { $script:FallbackScheme = Get-ActiveScheme }
            if (-not (Test-Path -LiteralPath $script:WinUiRestoreFile)) { @{ Scheme=$script:FallbackScheme; SavedAt=(Get-Date).ToString('s') } | ConvertTo-Json | Set-Content -LiteralPath $script:WinUiRestoreFile -Encoding UTF8 }
            $plan = [pscustomobject]@{ SchemeName=$script:CustomTuningSchemeName; Description='Customer controlled Windows power tuning'; Mode='Custom Tuning'; CpuMinAc=$settings.CpuMinAc; CpuMaxAc=$settings.CpuMaxAc; CpuBoostAc=$settings.CpuBoostAc; CpuMinDc=$settings.CpuMinDc; CpuMaxDc=$settings.CpuMaxDc; CpuBoostDc=$settings.CpuBoostDc; CoolingPolicy=1; PcieLinkState=if($settings.DisablePcieSaving){0}else{1}; WirelessSaving=if($settings.DisableWirelessSaving){0}else{2}; UsbSelectiveSuspend=if($settings.DisableUsbSuspend){0}else{1}; DisableIdleSleep=$settings.KeepAwake; DiskIdleAc=if($settings.KeepAwake){0}else{20}; DiskIdleDc=if($settings.KeepAwake){0}else{10}; SleepAfterAc=if($settings.KeepAwake){0}else{30}; SleepAfterDc=if($settings.KeepAwake){0}else{15}; HibernateAfterAc=if($settings.KeepAwake){0}else{120}; HibernateAfterDc=if($settings.KeepAwake){0}else{60}; CloseBackground=$false; Summary=('Custom Windows tuning: ' + $settings.Name); Notes=@('Stored in a dedicated GameBoost power plan and can be restored.') }
            $scheme = Ensure-GameBoostPowerScheme -Plan $plan
            $result = Invoke-PowerCfg @('/setactive',$scheme)
            $ok = ($result.ExitCode -eq 0)
            [pscustomobject]@{ Action='ApplyTuning'; Allowed=$ok; Message=if($ok){'Custom tuning is active: ' + $WinUiTuningPreset}else{'Windows rejected the custom power profile.'}; Scheme=$scheme } | ConvertTo-Json
        }
        'UpdateCheck' {
            $update = Test-GameBoostUpdate
            if ($update) { [pscustomobject]@{ Action='UpdateCheck'; Available=$true; Version=$update.Version; DownloadUrl=$update.DownloadUri; Notes=$update.Notes } | ConvertTo-Json }
            else { [pscustomobject]@{ Action='UpdateCheck'; Available=$false; Version=$script:AppVersion; Message='Already up to date or update service unavailable.' } | ConvertTo-Json }
        }
        'Launch' {
            $game = @(Get-SteamGames | Where-Object { $_.Name -eq $WinUiGameName } | Select-Object -First 1)
            if ($game.Count -eq 0) { [pscustomobject]@{ Action='Launch'; Allowed=$false; Message='Selected game was not found. Rescan the library.' } | ConvertTo-Json; break }
            if ($WinUiLaunchMode -eq 'Extreme' -and -not (Test-GameBoostFeature 'extremeOptimization')) { [pscustomobject]@{ Action='Launch'; Allowed=$false; Message='Professional license is required for Extreme launch.' } | ConvertTo-Json; break }
            if (-not (Test-Path -LiteralPath $script:WinUiRestoreFile)) { @{ Scheme=(Get-ActiveScheme); SavedAt=(Get-Date).ToString('s') } | ConvertTo-Json | Set-Content -LiteralPath $script:WinUiRestoreFile -Encoding UTF8 }
            if ($WinUiLaunchMode -eq 'Extreme') { [void](Set-GameBoostPowerActive -Extreme); [void](Set-WindowsGameSettings -Extreme); [void](Enable-LowLatencyTimer) } else { [void](Set-GameBoostPowerActive); Disable-LowLatencyTimer; [void](Set-WindowsGameSettings) }
            if ($game[0].Exe) { [void](Set-HighPerformanceGpu $game[0].Exe) }
            if ($game[0].Source -eq 'Steam' -and $game[0].AppId) { Start-Process ('steam://rungameid/' + $game[0].AppId) } elseif ($game[0].Exe) { Start-Process -FilePath $game[0].Exe -WorkingDirectory (Split-Path $game[0].Exe) } else { [pscustomobject]@{ Action='Launch'; Allowed=$false; Message='The selected game has no launch target.' } | ConvertTo-Json; break }
            [pscustomobject]@{ Action='Launch'; Allowed=$true; Message=($game[0].Name + ' launch requested with ' + $WinUiLaunchMode + ' mode.') } | ConvertTo-Json
        }
        'LaunchPath' {
            if (-not $WinUiGamePath -or -not (Test-Path -LiteralPath $WinUiGamePath -PathType Leaf) -or [IO.Path]::GetExtension($WinUiGamePath) -ne '.exe') { [pscustomobject]@{ Action='LaunchPath'; Allowed=$false; Message='Select a valid executable file.' } | ConvertTo-Json; break }
            if ($WinUiLaunchMode -eq 'Extreme' -and -not (Test-GameBoostFeature 'extremeOptimization')) { [pscustomobject]@{ Action='LaunchPath'; Allowed=$false; Message='Professional license is required for Extreme launch.' } | ConvertTo-Json; break }
            if (-not (Test-Path -LiteralPath $script:WinUiRestoreFile)) { @{ Scheme=(Get-ActiveScheme); SavedAt=(Get-Date).ToString('s') } | ConvertTo-Json | Set-Content -LiteralPath $script:WinUiRestoreFile -Encoding UTF8 }
            if ($WinUiLaunchMode -eq 'Extreme') { [void](Set-GameBoostPowerActive -Extreme); [void](Set-WindowsGameSettings -Extreme); [void](Enable-LowLatencyTimer) } else { [void](Set-GameBoostPowerActive); Disable-LowLatencyTimer; [void](Set-WindowsGameSettings) }
            [void](Set-HighPerformanceGpu $WinUiGamePath)
            Start-Process -FilePath $WinUiGamePath -WorkingDirectory (Split-Path $WinUiGamePath)
            [pscustomobject]@{ Action='LaunchPath'; Allowed=$true; Message=([IO.Path]::GetFileNameWithoutExtension($WinUiGamePath) + ' launch requested with ' + $WinUiLaunchMode + ' mode.') } | ConvertTo-Json
        }
        'Preflight' {
            $targetPath = $WinUiGamePath
            if (-not $targetPath -and $WinUiGameName) { $found = @(Get-SteamGames | Where-Object { $_.Name -eq $WinUiGameName } | Select-Object -First 1); if ($found.Count -gt 0) { $targetPath = [string]$found[0].Exe } }
            $gpu = Get-GpuStatus
            $limit = if ($script:SystemProfile.IsLaptop) { 84 } else { [int]$script:ThermalLimitC }
            $issues = @()
            if (-not (Test-GameBoostFeature 'extremeOptimization')) { $issues += 'Professional license is required.' }
            if (-not (Test-GameBoostAdministrator)) { $issues += 'Run GameBoost as administrator for the full system policy.' }
            if (-not $targetPath -or -not (Test-Path -LiteralPath $targetPath -PathType Leaf)) { $issues += 'No valid game executable was found.' }
            $temp = $null; try { $temp = [int]$gpu.Temp } catch {}
            if ($temp -ne $null -and $temp -ge $limit) { $issues += ('GPU temperature is ' + $temp + ' C; cool below ' + $limit + ' C before competitive mode.') }
            $scheme = Get-ActiveScheme
            $summary = 'Game: ' + $WinUiGameName + '; active scheme: ' + $scheme + '; GPU: ' + $(if($temp -ne $null){$temp.ToString() + ' C'}else{'unavailable'}) + '; limit: ' + $limit + ' C.'
            if ($issues.Count -eq 0) { [pscustomobject]@{ Action='Preflight'; Allowed=$true; Message=($summary + ' Preflight passed; no settings were changed.') } | ConvertTo-Json }
            else { [pscustomobject]@{ Action='Preflight'; Allowed=$false; Message=($summary + ' ' + ($issues -join ' ')) } | ConvertTo-Json }
        }
    }
    exit 0
}

if ($TestScan) {
    $games = @(Get-SteamGames | Sort-Object Name -Unique)
    $gpuCount = 0
    $gameSettingsReady = Set-WindowsGameSettings
    foreach ($game in $games) {
        if ($game.Exe -and (Set-HighPerformanceGpu $game.Exe)) { $gpuCount++ }
    }
    [pscustomobject]@{
        ScannedAt = (Get-Date).ToString('s')
        Hardware = $script:SystemProfile
        AdaptivePlan = $script:AdaptivePlan
        ExtremePlan = $script:ExtremePlan
        PowerScheme = [pscustomobject]@{
            Name = $script:PowerSchemeName
            Guid = $script:OptimizedScheme
            Ready = $script:PowerSchemeReady
            Message = $script:PowerSchemeMessage
        }
        WindowsGameSettingsReady = $gameSettingsReady
        GameCount = $games.Count
        GpuOptimizedCount = $gpuCount
        LaunchableCount = (Get-LaunchableGameCount $games)
        ActiveScheme = (Get-ActiveScheme)
        Games = @($games | ForEach-Object {
            [pscustomobject]@{
                Name = $_.Name
                Source = $_.Source
                AppId = $_.AppId
                Status = (Get-GameStatusText $_)
                Exe = if ($_.Exe) { [string]$_.Exe } else { $null }
                InstallPath = $_.InstallPath
            }
        })
    } | ConvertTo-Json -Depth 4
    exit 0
}

if ($SelfTest) {
    Invoke-GameBoostSelfTest | ConvertTo-Json -Depth 5
    exit 0
}

if ($SmartGlobalDiagnostics) {
    Get-SmartGlobalDiagnostics | ConvertTo-Json -Depth 5
    exit 0
}

if ($LicenseSmokeTest) {
    [pscustomobject][ordered]@{
        TestedAt = (Get-Date).ToString('s')
        License = $script:LicenseState
        FreeFeatures = (Get-GameBoostFeatureSet 'free')
        ProFeatures = (Get-GameBoostFeatureSet 'pro')
    } | ConvertTo-Json -Depth 5
    exit 0
}

function Set-Status {
    param([string]$Title, [string]$Detail, [System.Drawing.Color]$Color)
    $statusTitle.Text = $Title
    $statusTitle.ForeColor = $Color
    $statusDetail.Text = $Detail
}

function Get-SelectedGameText {
    param($Game)
    if (-not $Game) { return T 'SelectedNone' }
    $prefix = 'Selected: '
    if ($script:Language -eq 'zh-CN') { $prefix = '已选择：' }
    return $prefix + $Game.Name
}

function Get-ExtremeStatusDetail {
    param(
        [int]$GpuCount,
        [int]$LaunchableCount,
        [int]$ClosedCount,
        [int]$PriorityCount,
        [bool]$PowerReady,
        [bool]$SystemPolicyReady,
        [bool]$TimerReady
    )

    if ($script:Language -eq 'zh-CN') {
        $detail = $GpuCount.ToString() + ' 个 GPU 配置已就绪；' + $LaunchableCount.ToString() + ' 个游戏可用极限模式启动；已关闭 ' + $ClosedCount.ToString() + ' 个后台进程。'
        if ($PriorityCount -gt 0) { $detail += ' 已给 ' + $PriorityCount.ToString() + ' 个正在运行的游戏设为高优先级。' }
        if (-not $TimerReady) { $detail += ' 低延迟计时器启用失败。' }
        if (-not $PowerReady) { $detail += ' 电源计划切换失败，正在使用系统当前计划。' }
        if (-not $SystemPolicyReady) {
            if ($script:ExtremeSystemPolicyState -eq 'requires_admin') { $detail += ' 系统级注册表策略需要管理员权限，已跳过；其余最佳优化已生效。' }
            else { $detail += ' 系统级注册表策略未能写入；其余最佳优化已生效。' }
        }
        return $detail
    }

    $detail = $GpuCount.ToString() + ' GPU profiles ready; ' + $LaunchableCount.ToString() + ' games can launch in extreme mode; ' + $ClosedCount.ToString() + ' background processes closed.'
    if ($PriorityCount -gt 0) { $detail += ' ' + $PriorityCount.ToString() + ' running games set to high priority.' }
    if (-not $TimerReady) { $detail += ' Low-latency timer failed.' }
    if (-not $PowerReady) { $detail += ' Power profile fallback is in use.' }
    if (-not $SystemPolicyReady) {
        if ($script:ExtremeSystemPolicyState -eq 'requires_admin') { $detail += ' Admin-only registry policy was skipped; remaining extreme settings are active.' }
        else { $detail += ' System registry policy could not be applied; remaining extreme settings are active.' }
    }
    return $detail
}

function Launch-SelectedGame {
    if (-not $script:SelectedGame) {
        Set-Status (T 'SelectGame') (T 'SelectGameDetail') ([System.Drawing.Color]::FromArgb(220,160,40))
        return
    }
    $useExtreme = [bool]$script:ExtremeModeActive
    if ($useExtreme) {
        $script:SystemProfile = Get-SystemProfile
        $script:ExtremePlan = Get-ExtremePlan -Profile $script:SystemProfile
    }

    $powerReady = if ($useExtreme) { Set-GameBoostPowerActive -Extreme } else { Set-GameBoostPowerActive }
    if ($useExtreme) {
        [void](Set-WindowsGameSettings -Extreme)
        [void](Set-ExtremeSystemGamePolicy)
        [void](Enable-LowLatencyTimer)
    } else {
        Disable-LowLatencyTimer
        [void](Set-WindowsGameSettings)
    }
    [void](Set-HighPerformanceGpu $script:SelectedGame.Exe)
    $activePlan = if ($useExtreme) { $script:ExtremePlan } else { $script:AdaptivePlan }
    $closeNames = if ($useExtreme) { $script:ExtremeCloseProcesses } else { $script:CloseProcesses }
    if ($activePlan.CloseBackground) { [void](Stop-GameBoostBackgroundProcesses $closeNames) }
    if ($script:SelectedGame.Source -eq 'Steam' -and $script:SelectedGame.AppId) {
        Start-Process ('steam://rungameid/' + $script:SelectedGame.AppId)
    } elseif ($script:SelectedGame.Exe) {
        Start-Process -FilePath $script:SelectedGame.Exe -WorkingDirectory (Split-Path $script:SelectedGame.Exe)
    }
    if ($useExtreme) { [void](Set-GameProcessPriority -Game $script:SelectedGame -WaitSeconds 12) }
    Update-GameLearningProfile -Game $script:SelectedGame -Event 'SessionStart' -Gpu (Get-GpuStatus)
    $script:LastLaunch = Get-Date
    $detail = $script:SelectedGame.Name + ' is launching with the ' + $activePlan.Mode + ' profile.'
    if (-not $powerReady) { $detail += ' Power profile fallback is in use.' }
    $statusText = if ($useExtreme) { T 'ExtremeActive' } else { T 'OptimizationActive' }
    Set-Status $statusText $detail ([System.Drawing.Color]::FromArgb(67,190,120))
    $launchButton.Text = 'ACTIVE'
    $launchButton.BackColor = [System.Drawing.Color]::FromArgb(35,135,85)
}

$form = New-Object System.Windows.Forms.Form
$form.Text = T 'WindowTitle'
$form.Size = New-Object System.Drawing.Size(1200,760)
$form.MinimumSize = New-Object System.Drawing.Size(1200,720)
$form.StartPosition = 'CenterScreen'
$form.BackColor = [System.Drawing.Color]::FromArgb(12,15,20)
$form.BackgroundImage = [System.Drawing.Image]::FromFile($script:BackgroundImagePath)
$form.BackgroundImageLayout = 'Stretch'
$script:BackgroundBitmap = New-Object System.Drawing.Bitmap($script:BackgroundImagePath)
$form.Icon = [System.Drawing.Icon]::FromHandle($script:BackgroundBitmap.GetHicon())
$form.ForeColor = [System.Drawing.Color]::White
$form.Font = New-Object System.Drawing.Font('Microsoft YaHei UI',10)

$header = New-Object GameBoostUi.GlassPanel
$header.Dock = 'Top'; $header.Height = 104; $header.GlassColor = [System.Drawing.Color]::FromArgb(226,10,17,25); $header.BorderColor = [System.Drawing.Color]::FromArgb(105,126,149,165)
$form.Controls.Add($header)

$title = New-Object System.Windows.Forms.Label
$title.Text = 'GAMEBOOST-HAXU'; $title.Font = New-Object System.Drawing.Font('Microsoft YaHei UI',22,[System.Drawing.FontStyle]::Bold)
$title.Location = New-Object System.Drawing.Point(24,14); $title.AutoSize = $true
$header.Controls.Add($title)

$subtitle = New-Object System.Windows.Forms.Label
$subtitle.Text = T 'Subtitle'
$subtitle.ForeColor = [System.Drawing.Color]::FromArgb(174,194,208); $subtitle.Location = New-Object System.Drawing.Point(28,62); $subtitle.AutoSize = $true
$header.Controls.Add($subtitle)

$gpuLabel = New-Object System.Windows.Forms.Label
$gpuLabel.Text = 'GPU: reading...'; $gpuLabel.TextAlign = 'MiddleRight'; $gpuLabel.Anchor = 'Top,Right'
$gpuLabel.Location = New-Object System.Drawing.Point(865,24); $gpuLabel.Size = New-Object System.Drawing.Size(310,42)
$gpuLabel.ForeColor = [System.Drawing.Color]::FromArgb(196,214,226)
$header.Controls.Add($gpuLabel)

$languageButton = New-Object System.Windows.Forms.Button
$languageButton.Text = T 'Language'; $languageButton.Location = New-Object System.Drawing.Point(742,60); $languageButton.Size = New-Object System.Drawing.Size(104,28)
$languageButton.FlatStyle = 'Flat'; $languageButton.BackColor = [System.Drawing.Color]::FromArgb(33,42,54); $languageButton.ForeColor = [System.Drawing.Color]::White
$header.Controls.Add($languageButton)

$adminButton = New-Object System.Windows.Forms.Button
$adminButton.Text = if (Test-GameBoostAdministrator) { 'ADMIN' } elseif ($script:Language -eq 'zh-CN') { '管理员增强' } else { 'ADMIN MODE' }
$adminButton.Location = New-Object System.Drawing.Point(724,22); $adminButton.Size = New-Object System.Drawing.Size(122,28)
$adminButton.FlatStyle = 'Flat'; $adminButton.BackColor = if (Test-GameBoostAdministrator) { [System.Drawing.Color]::FromArgb(35,135,85) } else { [System.Drawing.Color]::FromArgb(190,150,70) }; $adminButton.ForeColor = [System.Drawing.Color]::White
$adminButton.FlatAppearance.BorderColor = [System.Drawing.Color]::FromArgb(90,105,120)
$adminButton.Add_Click({ Restart-GameBoostElevated })
$header.Controls.Add($adminButton)

$headerLicenseButton = New-Object System.Windows.Forms.Button
$headerLicenseButton.Text = if ($script:Language -eq 'zh-CN') { '输入授权码' } else { 'LICENSE KEY' }
$headerLicenseButton.Location = New-Object System.Drawing.Point(568,22); $headerLicenseButton.Size = New-Object System.Drawing.Size(144,28)
$headerLicenseButton.FlatStyle = 'Flat'; $headerLicenseButton.BackColor = [System.Drawing.Color]::FromArgb(46,115,210); $headerLicenseButton.ForeColor = [System.Drawing.Color]::White
$header.Controls.Add($headerLicenseButton)

$updateButton = New-Object System.Windows.Forms.Button
$updateButton.Text = if ($script:Language -eq 'zh-CN') { '检查更新' } else { 'CHECK UPDATE' }
$updateButton.Location = New-Object System.Drawing.Point(450,22); $updateButton.Size = New-Object System.Drawing.Size(108,28)
$updateButton.FlatStyle = 'Flat'; $updateButton.BackColor = [System.Drawing.Color]::FromArgb(33,42,54); $updateButton.ForeColor = [System.Drawing.Color]::White
$header.Controls.Add($updateButton)

$left = New-Object GameBoostUi.GlassPanel
$left.Location = New-Object System.Drawing.Point(20,126); $left.Size = New-Object System.Drawing.Size(720,584)
$left.Anchor = 'Top,Bottom,Left'; $left.GlassColor = [System.Drawing.Color]::FromArgb(226,12,20,29); $left.BorderColor = [System.Drawing.Color]::FromArgb(100,122,145,162)
$form.Controls.Add($left)

$gamesLabel = New-Object System.Windows.Forms.Label
$gamesLabel.Text = T 'Games'; $gamesLabel.Font = New-Object System.Drawing.Font('Microsoft YaHei UI',11,[System.Drawing.FontStyle]::Bold)
$gamesLabel.Location = New-Object System.Drawing.Point(18,16); $gamesLabel.AutoSize = $true
$left.Controls.Add($gamesLabel)

$list = New-Object System.Windows.Forms.ListView
$list.View = 'Details'; $list.FullRowSelect = $true; $list.HideSelection = $false; $list.MultiSelect = $false
$list.Location = New-Object System.Drawing.Point(18,52); $list.Size = New-Object System.Drawing.Size(684,380)
$list.Anchor = 'Top,Bottom,Left,Right'; $list.BackColor = [System.Drawing.Color]::FromArgb(25,31,38); $list.ForeColor = [System.Drawing.Color]::White
$list.Font = New-Object System.Drawing.Font('Microsoft YaHei UI',10)
[void]$list.Columns.Add((T 'Game'),438); [void]$list.Columns.Add((T 'Source'),105); [void]$list.Columns.Add((T 'Status'),136)
$left.Controls.Add($list)

$scanButton = New-Object System.Windows.Forms.Button
$scanButton.Text = T 'Rescan'; $scanButton.Location = New-Object System.Drawing.Point(18,452); $scanButton.Size = New-Object System.Drawing.Size(96,36)
$scanButton.Anchor = 'Bottom,Left'; $scanButton.FlatStyle = 'Flat'; $scanButton.BackColor = [System.Drawing.Color]::FromArgb(33,42,54); $scanButton.ForeColor = [System.Drawing.Color]::White
$left.Controls.Add($scanButton)

$addButton = New-Object System.Windows.Forms.Button
$addButton.Text = T 'AddExe'; $addButton.Location = New-Object System.Drawing.Point(122,452); $addButton.Size = New-Object System.Drawing.Size(96,36)
$addButton.Anchor = 'Bottom,Left'; $addButton.FlatStyle = 'Flat'; $addButton.BackColor = [System.Drawing.Color]::FromArgb(33,42,54); $addButton.ForeColor = [System.Drawing.Color]::White
$left.Controls.Add($addButton)

$optimizeAllButton = New-Object System.Windows.Forms.Button
$optimizeAllButton.Text = T 'OptimizeAll'; $optimizeAllButton.Location = New-Object System.Drawing.Point(240,452); $optimizeAllButton.Size = New-Object System.Drawing.Size(142,36)
$optimizeAllButton.Anchor = 'Bottom,Left'; $optimizeAllButton.FlatStyle = 'Flat'; $optimizeAllButton.BackColor = [System.Drawing.Color]::FromArgb(46,115,210); $optimizeAllButton.ForeColor = [System.Drawing.Color]::White
$left.Controls.Add($optimizeAllButton)

$extremeButton = New-Object System.Windows.Forms.Button
$extremeButton.Text = T 'OptimizeExtreme'; $extremeButton.Location = New-Object System.Drawing.Point(390,452); $extremeButton.Size = New-Object System.Drawing.Size(142,36)
$extremeButton.Anchor = 'Bottom,Left'; $extremeButton.FlatStyle = 'Flat'; $extremeButton.BackColor = [System.Drawing.Color]::FromArgb(205,80,55); $extremeButton.ForeColor = [System.Drawing.Color]::White
$extremeButton.Font = New-Object System.Drawing.Font('Microsoft YaHei UI',10,[System.Drawing.FontStyle]::Bold)
$left.Controls.Add($extremeButton)

$smartGlobalButton = New-Object System.Windows.Forms.Button
$smartGlobalButton.Text = T 'SmartGlobal'; $smartGlobalButton.Location = New-Object System.Drawing.Point(540,452); $smartGlobalButton.Size = New-Object System.Drawing.Size(162,36)
$smartGlobalButton.Anchor = 'Bottom,Left'; $smartGlobalButton.FlatStyle = 'Flat'; $smartGlobalButton.BackColor = [System.Drawing.Color]::FromArgb(80,90,105); $smartGlobalButton.ForeColor = [System.Drawing.Color]::White
$smartGlobalButton.Font = New-Object System.Drawing.Font('Microsoft YaHei UI',10,[System.Drawing.FontStyle]::Bold)
$left.Controls.Add($smartGlobalButton)

$metricsButton = New-Object System.Windows.Forms.Button
$metricsButton.Text = T 'Metrics'; $metricsButton.Location = New-Object System.Drawing.Point(18,508); $metricsButton.Size = New-Object System.Drawing.Size(88,36)
$metricsButton.Anchor = 'Bottom,Left'; $metricsButton.FlatStyle = 'Flat'; $metricsButton.BackColor = [System.Drawing.Color]::FromArgb(33,42,54); $metricsButton.ForeColor = [System.Drawing.Color]::White
$left.Controls.Add($metricsButton)

$networkButton = New-Object System.Windows.Forms.Button
$networkButton.Text = T 'Network'; $networkButton.Location = New-Object System.Drawing.Point(114,508); $networkButton.Size = New-Object System.Drawing.Size(88,36)
$networkButton.Anchor = 'Bottom,Left'; $networkButton.FlatStyle = 'Flat'; $networkButton.BackColor = [System.Drawing.Color]::FromArgb(33,42,54); $networkButton.ForeColor = [System.Drawing.Color]::White
$left.Controls.Add($networkButton)

$thermalButton = New-Object System.Windows.Forms.Button
$thermalButton.Text = T 'Thermal'; $thermalButton.Location = New-Object System.Drawing.Point(210,508); $thermalButton.Size = New-Object System.Drawing.Size(88,36)
$thermalButton.Anchor = 'Bottom,Left'; $thermalButton.FlatStyle = 'Flat'; $thermalButton.BackColor = [System.Drawing.Color]::FromArgb(35,135,85); $thermalButton.ForeColor = [System.Drawing.Color]::White
$left.Controls.Add($thermalButton)

$adviceButton = New-Object System.Windows.Forms.Button
$adviceButton.Text = if ($script:Language -eq 'zh-CN') { '竞技预检' } else { 'PREFLIGHT' }; $adviceButton.Location = New-Object System.Drawing.Point(306,508); $adviceButton.Size = New-Object System.Drawing.Size(88,36)
$adviceButton.Anchor = 'Bottom,Left'; $adviceButton.FlatStyle = 'Flat'; $adviceButton.BackColor = [System.Drawing.Color]::FromArgb(190,150,70); $adviceButton.ForeColor = [System.Drawing.Color]::White
$left.Controls.Add($adviceButton)

$profileButton = New-Object System.Windows.Forms.Button
$profileButton.Text = T 'Profile'; $profileButton.Location = New-Object System.Drawing.Point(402,508); $profileButton.Size = New-Object System.Drawing.Size(88,36)
$profileButton.Anchor = 'Bottom,Left'; $profileButton.FlatStyle = 'Flat'; $profileButton.BackColor = [System.Drawing.Color]::FromArgb(80,90,105); $profileButton.ForeColor = [System.Drawing.Color]::White
$left.Controls.Add($profileButton)

$tuningButton = New-Object System.Windows.Forms.Button
$tuningButton.Text = T 'Tuning'; $tuningButton.Location = New-Object System.Drawing.Point(498,508); $tuningButton.Size = New-Object System.Drawing.Size(88,36)
$tuningButton.Anchor = 'Bottom,Left'; $tuningButton.FlatStyle = 'Flat'; $tuningButton.BackColor = [System.Drawing.Color]::FromArgb(46,115,210); $tuningButton.ForeColor = [System.Drawing.Color]::White
$left.Controls.Add($tuningButton)

$chartButton = New-Object System.Windows.Forms.Button
$chartButton.Text = T 'Chart'; $chartButton.Location = New-Object System.Drawing.Point(594,508); $chartButton.Size = New-Object System.Drawing.Size(108,36)
$chartButton.Anchor = 'Bottom,Left'; $chartButton.FlatStyle = 'Flat'; $chartButton.BackColor = [System.Drawing.Color]::FromArgb(52,94,128); $chartButton.ForeColor = [System.Drawing.Color]::White
$left.Controls.Add($chartButton)

$right = New-Object GameBoostUi.GlassPanel
$right.Location = New-Object System.Drawing.Point(760,126); $right.Size = New-Object System.Drawing.Size(420,584)
$right.Anchor = 'Top,Bottom,Right'; $right.GlassColor = [System.Drawing.Color]::FromArgb(226,12,20,29); $right.BorderColor = [System.Drawing.Color]::FromArgb(100,122,145,162)
$form.Controls.Add($right)

$statusCaption = New-Object System.Windows.Forms.Label
$statusCaption.Text = T 'CurrentStatus'; $statusCaption.Font = New-Object System.Drawing.Font('Microsoft YaHei UI',11,[System.Drawing.FontStyle]::Bold)
$statusCaption.Location = New-Object System.Drawing.Point(20,18); $statusCaption.AutoSize = $true
$right.Controls.Add($statusCaption)

$statusTitle = New-Object System.Windows.Forms.Label
$statusTitle.Text = T 'Ready'; $statusTitle.Font = New-Object System.Drawing.Font('Microsoft YaHei UI',18,[System.Drawing.FontStyle]::Bold)
$statusTitle.ForeColor = [System.Drawing.Color]::FromArgb(220,160,40); $statusTitle.Location = New-Object System.Drawing.Point(20,54); $statusTitle.AutoSize = $true
$right.Controls.Add($statusTitle)

$statusDetail = New-Object System.Windows.Forms.Label
$statusDetail.Text = T 'ReadyDetail'; $statusDetail.ForeColor = [System.Drawing.Color]::FromArgb(165,172,184)
$statusDetail.Location = New-Object System.Drawing.Point(22,98); $statusDetail.Size = New-Object System.Drawing.Size(376,92)
$right.Controls.Add($statusDetail)

$schemeLabel = New-Object System.Windows.Forms.Label
$schemeLabel.Location = New-Object System.Drawing.Point(22,208); $schemeLabel.Size = New-Object System.Drawing.Size(376,76)
$right.Controls.Add($schemeLabel)

$advancedLabel = New-Object System.Windows.Forms.Label
$advancedLabel.Location = New-Object System.Drawing.Point(22,292); $advancedLabel.Size = New-Object System.Drawing.Size(376,136)
$advancedLabel.ForeColor = [System.Drawing.Color]::FromArgb(174,194,208)
$right.Controls.Add($advancedLabel)

$selectedLabel = New-Object System.Windows.Forms.Label
$selectedLabel.Text = T 'SelectedNone'; $selectedLabel.Location = New-Object System.Drawing.Point(22,434); $selectedLabel.Size = New-Object System.Drawing.Size(376,28)
$right.Controls.Add($selectedLabel)

$licenseButton = New-Object System.Windows.Forms.Button
$licenseButton.Text = if ($script:Language -eq 'zh-CN') { '输入授权码' } else { 'ENTER LICENSE KEY' }; $licenseButton.Location = New-Object System.Drawing.Point(22,462); $licenseButton.Size = New-Object System.Drawing.Size(376,30)
$licenseButton.Anchor = 'Bottom,Left,Right'; $licenseButton.FlatStyle = 'Flat'; $licenseButton.BackColor = [System.Drawing.Color]::FromArgb(50,55,64); $licenseButton.ForeColor = [System.Drawing.Color]::White
$right.Controls.Add($licenseButton)

$launchButton = New-Object System.Windows.Forms.Button
$launchButton.Text = T 'Launch'; $launchButton.Location = New-Object System.Drawing.Point(22,500); $launchButton.Size = New-Object System.Drawing.Size(376,40)
$launchButton.Anchor = 'Bottom,Left,Right'; $launchButton.FlatStyle = 'Flat'; $launchButton.BackColor = [System.Drawing.Color]::FromArgb(46,115,210); $launchButton.ForeColor = [System.Drawing.Color]::White
$launchButton.Font = New-Object System.Drawing.Font('Microsoft YaHei UI',11,[System.Drawing.FontStyle]::Bold)
$right.Controls.Add($launchButton)

$restoreButton = New-Object System.Windows.Forms.Button
$restoreButton.Text = T 'Restore'; $restoreButton.Location = New-Object System.Drawing.Point(22,548); $restoreButton.Size = New-Object System.Drawing.Size(376,28)
$restoreButton.Anchor = 'Bottom,Left,Right'; $restoreButton.FlatStyle = 'Flat'; $restoreButton.BackColor = [System.Drawing.Color]::FromArgb(50,55,64); $restoreButton.ForeColor = [System.Drawing.Color]::White
$right.Controls.Add($restoreButton)

function Refresh-GameList {
    $list.Items.Clear(); $script:Games.Clear()
    $games = @(Get-SteamGames | Sort-Object Name -Unique)
    foreach ($game in $games) {
        if ($game.Exe) { [void](Set-HighPerformanceGpu $game.Exe) }
        [void]$script:Games.Add($game)
        $item = New-Object System.Windows.Forms.ListViewItem($game.Name)
        [void]$item.SubItems.Add($game.Source)
        [void]$item.SubItems.Add((Get-GameStatusText $game))
        if (-not $game.Exe) { $item.ForeColor = [System.Drawing.Color]::FromArgb(220,160,40) }
        $item.Tag = $game; [void]$list.Items.Add($item)
    }
    $gamesLabel.Text = (T 'Games') + '  (' + $games.Count + ')'
    $gpuCount = @($games | Where-Object Exe).Count
    $launchableCount = Get-LaunchableGameCount $games
    Set-Status (T 'ScanComplete') ($gpuCount.ToString() + ' GPU profiles ready. ' + $launchableCount.ToString() + ' games can launch with FPS mode.') ([System.Drawing.Color]::FromArgb(67,190,120))
    $optimizeAllButton.Text = T 'OptimizeAll'
    $optimizeAllButton.BackColor = [System.Drawing.Color]::FromArgb(46,115,210)
    if (-not $script:ExtremeModeActive) {
        $extremeButton.Text = T 'OptimizeExtreme'
        $extremeButton.BackColor = [System.Drawing.Color]::FromArgb(205,80,55)
    }
}

function Invoke-NormalOptimizationCore {
    if ($script:Games.Count -eq 0) { Refresh-GameList }
    $powerReady = Set-GameBoostPowerActive
    Disable-LowLatencyTimer
    [void](Set-WindowsGameSettings)
    $gpuCount = 0
    foreach ($game in $script:Games) {
        if ($game.Exe -and (Set-HighPerformanceGpu $game.Exe)) { $gpuCount++ }
    }
    if ($script:AdaptivePlan.CloseBackground) {
        $closedCount = Stop-GameBoostBackgroundProcesses $script:CloseProcesses
    } else {
        $closedCount = 0
    }
    $launchableCount = Get-LaunchableGameCount @($script:Games)
    return [pscustomobject]@{
        PowerReady = $powerReady
        GpuCount = $gpuCount
        LaunchableCount = $launchableCount
        ClosedCount = $closedCount
    }
}

function Optimize-AllGames {
    $result = Invoke-NormalOptimizationCore
    $detail = $result.GpuCount.ToString() + ' GPU profiles ready. ' + $result.LaunchableCount.ToString() + ' games will launch under the ' + $script:AdaptivePlan.Mode + ' profile.'
    if (-not $result.PowerReady) { $detail += ' Power profile fallback is in use.' }
    Set-Status 'ALL FPS MODE ACTIVE' $detail ([System.Drawing.Color]::FromArgb(67,190,120))
    $optimizeAllButton.Text = T 'Active'
    $optimizeAllButton.BackColor = [System.Drawing.Color]::FromArgb(35,135,85)
    $extremeButton.Text = T 'OptimizeExtreme'
    $extremeButton.BackColor = [System.Drawing.Color]::FromArgb(205,80,55)
}

function Invoke-ExtremeOptimizationCore {
    if ($script:Games.Count -eq 0) { Refresh-GameList }
    $script:SystemProfile = Get-SystemProfile
    $script:ExtremePlan = Get-ExtremePlan -Profile $script:SystemProfile
    $script:ExtremeScheme = Ensure-GameBoostPowerScheme -Plan $script:ExtremePlan

    $powerReady = Set-GameBoostPowerActive -Extreme
    [void](Set-WindowsGameSettings -Extreme)
    $systemPolicyReady = Set-ExtremeSystemGamePolicy
    $timerReady = Enable-LowLatencyTimer

    $gpuCount = 0
    foreach ($game in $script:Games) {
        if ($game.Exe -and (Set-HighPerformanceGpu $game.Exe)) { $gpuCount++ }
    }

    $closedCount = Stop-GameBoostBackgroundProcesses $script:ExtremeCloseProcesses
    $priorityCount = Set-RunningGamePriorities @($script:Games)
    $launchableCount = Get-LaunchableGameCount @($script:Games)
    return [pscustomobject]@{
        GpuCount = $gpuCount
        LaunchableCount = $launchableCount
        ClosedCount = $closedCount
        PriorityCount = $priorityCount
        PowerReady = $powerReady
        SystemPolicyReady = $systemPolicyReady
        TimerReady = $timerReady
    }
}

function Optimize-ExtremeAllGames {
    if (-not (Assert-GameBoostFeature 'extremeOptimization' (T 'OptimizeExtreme'))) { return }
    $result = Invoke-ExtremeOptimizationCore
    $detail = Get-ExtremeStatusDetail -GpuCount $result.GpuCount -LaunchableCount $result.LaunchableCount -ClosedCount $result.ClosedCount -PriorityCount $result.PriorityCount -PowerReady $result.PowerReady -SystemPolicyReady $result.SystemPolicyReady -TimerReady $result.TimerReady

    Set-Status (T 'ExtremeActive') $detail ([System.Drawing.Color]::FromArgb(67,190,120))
    $extremeButton.Text = T 'Active'
    $extremeButton.BackColor = [System.Drawing.Color]::FromArgb(35,135,85)
    $optimizeAllButton.Text = T 'OptimizeAll'
    $optimizeAllButton.BackColor = [System.Drawing.Color]::FromArgb(46,115,210)
}

function Set-MetricsButtonState {
    if ($script:MetricsLoggingEnabled) {
        $metricsButton.Text = if ($script:Language -eq 'zh-CN') { '记录中' } else { 'LOG ON' }
        $metricsButton.BackColor = [System.Drawing.Color]::FromArgb(35,135,85)
    } else {
        $metricsButton.Text = T 'Metrics'
        $metricsButton.BackColor = [System.Drawing.Color]::FromArgb(33,42,54)
    }
}

function Set-ThermalButtonState {
    if ($script:ThermalGuardEnabled) {
        $thermalButton.Text = if ($script:Language -eq 'zh-CN') { '温控开' } else { 'THERMAL ON' }
        $thermalButton.BackColor = [System.Drawing.Color]::FromArgb(35,135,85)
    } else {
        $thermalButton.Text = if ($script:Language -eq 'zh-CN') { '温控关' } else { 'THERMAL OFF' }
        $thermalButton.BackColor = [System.Drawing.Color]::FromArgb(80,90,105)
    }
}

function Update-LicenseUiState {
    if (-not $extremeButton) { return }
    $proControls = @(
        @{ Control=$extremeButton; Feature='extremeOptimization'; Text=(T 'OptimizeExtreme') },
        @{ Control=$smartGlobalButton; Feature='smartGlobal'; Text=(T 'SmartGlobal') },
        @{ Control=$metricsButton; Feature='metricsLogging'; Text=(T 'Metrics') },
        @{ Control=$chartButton; Feature='metricsLogging'; Text=(T 'Chart') },
        @{ Control=$networkButton; Feature='networkOptimization'; Text=(T 'Network') },
        @{ Control=$thermalButton; Feature='thermalGuard'; Text=(T 'Thermal') },
        @{ Control=$adviceButton; Feature='gameProfiles'; Text=$(if ($script:Language -eq 'zh-CN') { '竞技预检' } else { 'PREFLIGHT' }) },
        @{ Control=$profileButton; Feature='gameProfiles'; Text=(T 'Profile') },
        @{ Control=$tuningButton; Feature='customTuning'; Text=(T 'Tuning') }
    )
    foreach ($item in $proControls) {
        $enabled = Test-GameBoostFeature $item.Feature
        $item.Control.Enabled = $enabled
        if (-not $enabled) {
            $item.Control.Text = if ($script:Language -eq 'zh-CN') { '专业版' } else { 'PRO' }
            $item.Control.BackColor = [System.Drawing.Color]::FromArgb(72,76,84)
        } elseif ($item.Control.Text -in @('专业版','PRO')) {
            $item.Control.Text = $item.Text
        }
    }
}

function Update-AdvancedLabels {
    if (-not $advancedLabel) { return }

    $metricsState = if ($script:MetricsLoggingEnabled) {
        if ($script:Language -eq 'zh-CN') { '性能记录：开启' } else { 'Metrics: on' }
    } else {
        if ($script:Language -eq 'zh-CN') { '性能记录：关闭' } else { 'Metrics: off' }
    }
    $thermalState = if ($script:ThermalGuardEnabled) {
        if ($script:Language -eq 'zh-CN') { '温控保护：' + $script:ThermalLimitC + ' C 降档' } else { 'Thermal: downshift at ' + $script:ThermalLimitC + ' C' }
    } else {
        if ($script:Language -eq 'zh-CN') { '温控保护：关闭' } else { 'Thermal: off' }
    }
    $networkState = if ($script:LastNetworkSummary) {
        if ($script:LastNetworkSummary.Length -gt 70) { $script:LastNetworkSummary.Substring(0,70) + '...' } else { $script:LastNetworkSummary }
    } else {
        if ($script:Language -eq 'zh-CN') { '网络优化：未运行' } else { 'Network optimization: not run' }
    }
    $adviceState = if ($script:LastAdviceSummary) {
        if ($script:LastAdviceSummary.Length -gt 80) { $script:LastAdviceSummary.Substring(0,80) + '...' } else { $script:LastAdviceSummary }
    } else {
        if ($script:Language -eq 'zh-CN') { '画像建议：选择游戏后生成' } else { 'Advice: select a game' }
    }
    $profileState = if ($script:SelectedGame) {
        $preferred = Get-GamePreferredMode $script:SelectedGame
        $effective = Get-EffectiveGameMode $script:SelectedGame
        if ($script:Language -eq 'zh-CN') { '游戏画像：' + $preferred + ' / 当前策略 ' + $effective } else { 'Profile: ' + $preferred + ' / effective ' + $effective }
    } else {
        if ($script:Language -eq 'zh-CN') { '游戏画像：未选择' } else { 'Profile: no game selected' }
    }

    $licenseState = if ($script:LicenseState -and $script:LicenseState.IsPro) {
        if ($script:Language -eq 'zh-CN') { '授权：专业版 / 设备 ' + $script:LicenseState.DeviceCount + '/' + $script:LicenseState.DeviceLimit } else { 'License: Pro / devices ' + $script:LicenseState.DeviceCount + '/' + $script:LicenseState.DeviceLimit }
    } else {
        if ($script:Language -eq 'zh-CN') { '授权：免费版' } else { 'License: Free' }
    }

    $advancedLabel.Text = $licenseState + "`r`n" + $metricsState + "`r`n" + $thermalState + "`r`n" + $profileState + "`r`n" + $networkState + "`r`n" + $adviceState
}

function Set-SmartGlobalButtonState {
    if ($script:SmartGlobalEnabled) {
        $smartGlobalButton.Text = if ($script:Language -eq 'zh-CN') { '全局开' } else { 'AUTO ON' }
        $smartGlobalButton.BackColor = [System.Drawing.Color]::FromArgb(35,135,85)
    } else {
        $smartGlobalButton.Text = T 'SmartGlobal'
        $smartGlobalButton.BackColor = [System.Drawing.Color]::FromArgb(80,90,105)
    }
}

function Get-SmartGlobalWaitingDetail {
    if ($script:Language -eq 'zh-CN') {
        return '正在后台监控已扫描游戏；检测到游戏运行时会自动启用最佳优化。'
    }
    return 'Monitoring scanned games; extreme optimization turns on automatically when a game is running.'
}

function Get-SmartGlobalActiveDetail {
    param($Match, $Result)
    if ($script:Language -eq 'zh-CN') {
        $detail = '检测到 ' + $Match.Game.Name + '，已自动启用最佳优化。退出游戏约 ' + $script:SmartGlobalRestoreGraceSeconds.ToString() + ' 秒后自动恢复。'
        if ($Result.ClosedCount -gt 0) { $detail += ' 已关闭 ' + $Result.ClosedCount.ToString() + ' 个后台进程。' }
        return $detail
    }
    $detail = 'Detected ' + $Match.Game.Name + '; extreme optimization is active. Auto-restore starts about ' + $script:SmartGlobalRestoreGraceSeconds.ToString() + ' seconds after exit.'
    if ($Result.ClosedCount -gt 0) { $detail += ' Closed ' + $Result.ClosedCount.ToString() + ' background processes.' }
    return $detail
}

function Get-SmartGlobalNormalDetail {
    param($Match, [int]$ClosedCount, [bool]$PowerReady)
    $preferred = Get-GamePreferredMode $Match.Game
    if ($script:Language -eq 'zh-CN') {
        $reason = if ($preferred -eq 'Normal') { '游戏画像指定普通优化' } else { '温度/历史画像建议普通优化' }
        $detail = '检测到 ' + $Match.Game.Name + '，' + $reason + '，已自动启用普通优化。'
        if ($ClosedCount -gt 0) { $detail += ' 已关闭 ' + $ClosedCount.ToString() + ' 个后台进程。' }
        if (-not $PowerReady) { $detail += ' 电源计划切换失败，正在使用系统当前计划。' }
        return $detail
    }
    $reason = if ($preferred -eq 'Normal') { 'profile prefers normal mode' } else { 'thermal or learning profile prefers normal mode' }
    $detail = 'Detected ' + $Match.Game.Name + '; ' + $reason + ', normal optimization is active.'
    if ($ClosedCount -gt 0) { $detail += ' Closed ' + $ClosedCount.ToString() + ' background processes.' }
    if (-not $PowerReady) { $detail += ' Power profile fallback is in use.' }
    return $detail
}

function Get-SmartGlobalRestoredDetail {
    if ($script:Language -eq 'zh-CN') {
        return '未检测到游戏运行，已恢复普通电源计划；智能全局继续待命。'
    }
    return 'No running game detected; normal power profile restored and auto global remains on standby.'
}

function Restore-GameBoostNormal {
    param(
        [switch]$KeepSmartGlobal,
        [string]$Title,
        [string]$Detail
    )

    $restoreGame = $script:SmartGlobalActiveGame
    $script:LastRestoreReason = if ($Title) { $Title } else { 'Manual restore' }
    Disable-LowLatencyTimer
    $script:ExtremeModeActive = $false
    $script:SmartGlobalActiveGame = $null
    $script:SmartGlobalActiveMode = ''
    $script:SmartGlobalNoGameSince = $null
    if (-not $KeepSmartGlobal) { $script:SmartGlobalEnabled = $false }

    if ($script:FallbackScheme) { [void](Invoke-PowerCfg @('/setactive', $script:FallbackScheme)) }
    if ($restoreGame) { Update-GameLearningProfile -Game $restoreGame -Event 'Restore' -Gpu (Get-GpuStatus) }
    if (-not $Title) { $Title = T 'NormalProfile' }
    if (-not $Detail) { $Detail = T 'NormalProfileDetail' }
    Set-Status $Title $Detail ([System.Drawing.Color]::FromArgb(150,158,170))
    $launchButton.Text = T 'Launch'; $launchButton.BackColor = [System.Drawing.Color]::FromArgb(46,115,210)
    $optimizeAllButton.Text = T 'OptimizeAll'; $optimizeAllButton.BackColor = [System.Drawing.Color]::FromArgb(46,115,210)
    $extremeButton.Text = T 'OptimizeExtreme'; $extremeButton.BackColor = [System.Drawing.Color]::FromArgb(205,80,55)
    Set-SmartGlobalButtonState
    Update-AdvancedLabels
}

function Enable-SmartGlobal {
    if (-not (Assert-GameBoostFeature 'smartGlobal' (T 'SmartGlobal'))) { return }
    if ($script:Games.Count -eq 0) { Refresh-GameList }
    $script:SmartGlobalEnabled = $true
    $script:SmartGlobalActiveGame = $null
    $script:SmartGlobalActiveMode = ''
    $script:SmartGlobalNoGameSince = $null
    $script:SmartGlobalNextCheck = [DateTime]::MinValue
    $script:SmartGlobalLastStatus = ''
    Set-SmartGlobalButtonState
    Set-Status (T 'SmartGlobalOn') (Get-SmartGlobalWaitingDetail) ([System.Drawing.Color]::FromArgb(67,190,120))
    Update-SmartGlobalMode -Force
}

function Disable-SmartGlobal {
    Restore-GameBoostNormal
}

function Toggle-SmartGlobal {
    if ($script:SmartGlobalEnabled) {
        Disable-SmartGlobal
    } else {
        Enable-SmartGlobal
    }
}

function Update-SmartGlobalMode {
    param([switch]$Force)

    if (-not (Test-GameBoostFeature 'smartGlobal')) { return }
    if (-not $script:SmartGlobalEnabled) { return }
    $now = Get-Date
    if (-not $Force -and $now -lt $script:SmartGlobalNextCheck) { return }
    $script:SmartGlobalNextCheck = $now.AddSeconds($script:SmartGlobalCheckSeconds)
    if ($script:Games.Count -eq 0) { return }

    $running = @(Get-RunningGameProcesses @($script:Games))
    if ($running.Count -gt 0) {
        $script:SmartGlobalNoGameSince = $null
        $match = $running[0]
        if ($script:SmartGlobalActiveGame) {
            $currentMatch = @($running | Where-Object { $_.Game.Name -eq $script:SmartGlobalActiveGame.Name } | Select-Object -First 1)
            if ($currentMatch.Count -gt 0) { $match = $currentMatch[0] }
        }

        $script:SelectedGame = $match.Game
        $selectedLabel.Text = Get-SelectedGameText $script:SelectedGame
        [void](Set-ProcessHighPriorityById $match.ProcessId)

        if ($script:ThermalGuardEnabled -and (Get-Date) -lt $script:ThermalThrottleUntil) {
            $detail = if ($script:Language -eq 'zh-CN') {
                '温控保护冷却中，暂不重新启用最佳优化。'
            } else {
                'Thermal guard cooldown is active; extreme mode is paused.'
            }
            if ($script:SmartGlobalLastStatus -ne 'ThermalCooldown') {
                Set-Status (T 'ThermalDownshift') $detail ([System.Drawing.Color]::FromArgb(220,160,40))
                $script:SmartGlobalLastStatus = 'ThermalCooldown'
            }
            return
        }

        $effectiveMode = Get-EffectiveGameMode $match.Game
        $sameGame = ($script:SmartGlobalActiveGame -and $script:SmartGlobalActiveGame.Name -eq $match.Game.Name)
        $sameMode = ($script:SmartGlobalActiveMode -eq $effectiveMode)
        if (-not $sameGame -or -not $sameMode) {
            $script:SmartGlobalActiveGame = $match.Game
            $script:SmartGlobalActiveMode = $effectiveMode
            if ($effectiveMode -eq 'Normal') {
                $result = Invoke-NormalOptimizationCore
                [void](Set-ProcessHighPriorityById $match.ProcessId)
                Update-GameLearningProfile -Game $match.Game -Event 'SessionStart' -Gpu (Get-GpuStatus)
                Set-Status (T 'OptimizationActive') (Get-SmartGlobalNormalDetail -Match $match -ClosedCount $result.ClosedCount -PowerReady $result.PowerReady) ([System.Drawing.Color]::FromArgb(67,190,120))
                $optimizeAllButton.Text = T 'Active'
                $optimizeAllButton.BackColor = [System.Drawing.Color]::FromArgb(35,135,85)
                $extremeButton.Text = T 'OptimizeExtreme'
                $extremeButton.BackColor = [System.Drawing.Color]::FromArgb(205,80,55)
            } else {
                $result = Invoke-ExtremeOptimizationCore
                [void](Set-ProcessHighPriorityById $match.ProcessId)
                Update-GameLearningProfile -Game $match.Game -Event 'SessionStart' -Gpu (Get-GpuStatus)
                Set-Status (T 'ExtremeActive') (Get-SmartGlobalActiveDetail -Match $match -Result $result) ([System.Drawing.Color]::FromArgb(67,190,120))
                $extremeButton.Text = T 'Active'
                $extremeButton.BackColor = [System.Drawing.Color]::FromArgb(35,135,85)
                $optimizeAllButton.Text = T 'OptimizeAll'
                $optimizeAllButton.BackColor = [System.Drawing.Color]::FromArgb(46,115,210)
            }
        }
        return
    }

    if ($script:SmartGlobalActiveGame) {
        if (-not $script:SmartGlobalNoGameSince) { $script:SmartGlobalNoGameSince = $now }
        if (($now - $script:SmartGlobalNoGameSince).TotalSeconds -ge $script:SmartGlobalRestoreGraceSeconds) {
            Restore-GameBoostNormal -KeepSmartGlobal -Title (T 'SmartGlobalRestored') -Detail (Get-SmartGlobalRestoredDetail)
        }
        return
    }

    if ($script:SmartGlobalLastStatus -ne 'Waiting') {
        Set-Status (T 'SmartGlobalWaiting') (Get-SmartGlobalWaitingDetail) ([System.Drawing.Color]::FromArgb(220,160,40))
        $script:SmartGlobalLastStatus = 'Waiting'
    }
}

$list.Add_SelectedIndexChanged({
    if ($list.SelectedItems.Count -gt 0) {
        $script:SelectedGame = $list.SelectedItems[0].Tag
        $selectedLabel.Text = Get-SelectedGameText $script:SelectedGame
        Update-AdvancedLabels
        $launchButton.Text = T 'Launch'; $launchButton.BackColor = [System.Drawing.Color]::FromArgb(46,115,210)
    }
})
$scanButton.Add_Click({ Refresh-GameList })
$languageButton.Add_Click({
    $script:Language = if ($script:Language -eq 'zh-CN') { 'en-US' } else { 'zh-CN' }
    Save-AppLanguage
    Update-InterfaceLanguage
})
$addButton.Add_Click({
    $dialog = New-Object System.Windows.Forms.OpenFileDialog
    $dialog.Filter = T 'ExeFilter'; $dialog.Title = T 'OpenExeTitle'
    if ($dialog.ShowDialog() -eq 'OK') {
        $game = [pscustomobject]@{ Name=[IO.Path]::GetFileNameWithoutExtension($dialog.FileName); Source='Manual'; AppId=$null; Exe=$dialog.FileName; InstallPath=(Split-Path $dialog.FileName); Optimized=$true }
        [void](Set-HighPerformanceGpu $game.Exe)
        [void]$script:Games.Add($game)
        $item = New-Object System.Windows.Forms.ListViewItem($game.Name); [void]$item.SubItems.Add('Manual'); [void]$item.SubItems.Add('Optimized'); $item.Tag=$game; [void]$list.Items.Add($item)
    }
})
$launchButton.Add_Click({ Launch-SelectedGame })
$optimizeAllButton.Add_Click({ Optimize-AllGames })
$extremeButton.Add_Click({ Optimize-ExtremeAllGames })
$smartGlobalButton.Add_Click({ Toggle-SmartGlobal })
$metricsButton.Add_Click({ Toggle-MetricsLogging })
$chartButton.Add_Click({ Show-MetricsChart })
$networkButton.Add_Click({ Invoke-NetworkGameOptimization })
$thermalButton.Add_Click({ Toggle-ThermalGuard })
$adviceButton.Add_Click({ Show-CompetitivePreflight })
$profileButton.Add_Click({ Open-GameProfileDialog })
$tuningButton.Add_Click({ Open-CustomTuningDialog })
$licenseButton.Add_Click({ Show-GameBoostLicenseActivationDialog })
$headerLicenseButton.Add_Click({ Show-GameBoostLicenseActivationDialog })
$updateButton.Add_Click({ Show-GameBoostUpdate })
$restoreButton.Add_Click({ Restore-GameBoostNormal })

function Update-InterfaceLanguage {
    $form.Text = T 'WindowTitle'; $subtitle.Text = T 'Subtitle'; $languageButton.Text = T 'Language'
    $adminButton.Text = if (Test-GameBoostAdministrator) { 'ADMIN' } elseif ($script:Language -eq 'zh-CN') { '管理员增强' } else { 'ADMIN MODE' }
    $gamesLabel.Text = (T 'Games') + '  (' + $script:Games.Count + ')'; $list.Columns[0].Text = T 'Game'; $list.Columns[1].Text = T 'Source'; $list.Columns[2].Text = T 'Status'
    $scanButton.Text = T 'Rescan'; $addButton.Text = T 'AddExe'; if ($optimizeAllButton.BackColor -ne [System.Drawing.Color]::FromArgb(35,135,85)) { $optimizeAllButton.Text = T 'OptimizeAll' }
    if ($extremeButton.BackColor -ne [System.Drawing.Color]::FromArgb(35,135,85)) { $extremeButton.Text = T 'OptimizeExtreme' } else { $extremeButton.Text = T 'Active' }
    Set-SmartGlobalButtonState
    Set-MetricsButtonState
    Set-ThermalButtonState
    $networkButton.Text = T 'Network'
    $adviceButton.Text = if ($script:Language -eq 'zh-CN') { '竞技预检' } else { 'PREFLIGHT' }
    $profileButton.Text = T 'Profile'
    $tuningButton.Text = T 'Tuning'
    $chartButton.Text = T 'Chart'
    $licenseButton.Text = if ($script:Language -eq 'zh-CN') { '输入授权码' } else { 'ENTER LICENSE KEY' }
    $headerLicenseButton.Text = if ($script:Language -eq 'zh-CN') { '输入授权码' } else { 'LICENSE KEY' }
    $updateButton.Text = if ($script:Language -eq 'zh-CN') { '检查更新' } else { 'CHECK UPDATE' }
    Update-LicenseUiState
    Update-AdvancedLabels
    $statusCaption.Text = T 'CurrentStatus'; $selectedLabel.Text = Get-SelectedGameText $script:SelectedGame
    if ($launchButton.BackColor -ne [System.Drawing.Color]::FromArgb(35,135,85)) { $launchButton.Text = T 'Launch' }; $restoreButton.Text = T 'Restore'
}

$timer = New-Object System.Windows.Forms.Timer
$timer.Interval = 3000
$timer.Add_Tick({
    $active = Get-ActiveScheme
    $isExtremeScheme = ($script:ExtremeScheme -and $active -eq $script:ExtremeScheme)
    $state = if ($isExtremeScheme) { T 'ExtremeState' } elseif ($active -eq $script:OptimizedScheme) { T 'ActiveState' } else { T 'Standby' }
    $displayPlan = if ($isExtremeScheme -and $script:ExtremePlan) { $script:ExtremePlan } else { $script:AdaptivePlan }
    $displaySchemeName = if ($isExtremeScheme) { $script:ExtremePowerSchemeName } else { $script:PowerSchemeName }
    $schemeLabel.Text = (T 'PcProfile') + ': ' + $displayPlan.Summary + "`r`n" + (T 'Power') + ': ' + $displaySchemeName + "`r`n" + (T 'State') + ': ' + $state
    $gpu = Get-GpuStatus
    if ($gpu) { $gpuLabel.Text = 'GPU  ' + $gpu.Temp + ' C   |   ' + $gpu.Load + '%   |   ' + $gpu.Power + ' W' }
    Invoke-ThermalGuard $gpu
    $match = Get-PrimaryRunningGame
    Update-AutoMetricsSession -Match $match
    $pingMs = Get-NetworkLatencyMs
    Write-MetricsSample -Gpu $gpu -ActiveScheme $active -Match $match -PingMs $pingMs
    Complete-NetworkGameOptimization
    Update-AdvancedLabels
    Update-SmartGlobalMode
    if ($script:LastLaunch -and ((Get-Date) - $script:LastLaunch).TotalMinutes -lt 2 -and ($active -eq $script:OptimizedScheme -or $isExtremeScheme)) {
        $statusTitle.Text = if ($isExtremeScheme) { T 'ExtremeActive' } else { T 'OptimizationActive' }
        $statusTitle.ForeColor = [System.Drawing.Color]::FromArgb(67,190,120)
    }
})

$form.Add_Shown({ Refresh-GameList; Set-MetricsButtonState; Set-ThermalButtonState; Update-LicenseUiState; Update-AdvancedLabels; $timer.Start() })
$form.Add_FormClosed({
    $timer.Stop()
    if ($script:NetworkJob) { Stop-Job -Job $script:NetworkJob -ErrorAction SilentlyContinue; Remove-Job -Job $script:NetworkJob -Force -ErrorAction SilentlyContinue }
    Disable-LowLatencyTimer
})

if ($UiSmokeTest) {
    $controls = @($form, $list, $scanButton, $addButton, $optimizeAllButton, $extremeButton, $smartGlobalButton, $metricsButton, $networkButton, $thermalButton, $adviceButton, $profileButton, $tuningButton, $chartButton, $licenseButton, $headerLicenseButton, $updateButton, $launchButton, $restoreButton)
    $missingControls = @($controls | Where-Object { $null -eq $_ })
    $layoutValid = -not $left.Bounds.IntersectsWith($right.Bounds)
    [pscustomobject]@{
        UiConstructed = ($missingControls.Count -eq 0 -and $layoutValid)
        ControlCount = $controls.Count
        LayoutValid = $layoutValid
        FormTitle = $form.Text
        BackgroundAvailable = (Test-Path -LiteralPath $script:BackgroundImagePath)
    } | ConvertTo-Json
    $form.Dispose()
    exit 0
}

[void]$form.ShowDialog()

