[CmdletBinding()]
param(
    [string]$InstallDir = (Join-Path $env:ProgramFiles 'KIM Quest Remote')
)

$ErrorActionPreference = 'Stop'
$ConfigDir = Join-Path $env:LOCALAPPDATA 'KIMQuestRemote'
$ConfigPath = Join-Path $ConfigDir 'config.json'
$TargetExe = Join-Path ([System.IO.Path]::GetFullPath($InstallDir)) 'KIMQuestRemoteHost.exe'

if (-not (Test-Path -LiteralPath $ConfigPath)) {
    if (-not (Test-Path -LiteralPath $TargetExe)) {
        throw 'Install KIM Remote first so this computer can generate its own identity.'
    }
    Start-Process -FilePath $TargetExe -WorkingDirectory $InstallDir
    $Deadline = (Get-Date).AddSeconds(8)
    while (-not (Test-Path -LiteralPath $ConfigPath) -and (Get-Date) -lt $Deadline) {
        Start-Sleep -Milliseconds 250
    }
    if (-not (Test-Path -LiteralPath $ConfigPath)) {
        throw "KIM Remote did not create its local config: $ConfigPath"
    }
}

$SecurePassword = Read-Host 'Enter the new pairing password' -AsSecureString
$Pointer = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecurePassword)
try {
    $PlainPassword = [Runtime.InteropServices.Marshal]::PtrToStringBSTR($Pointer)
} finally {
    [Runtime.InteropServices.Marshal]::ZeroFreeBSTR($Pointer)
}

$Effective = -join @(
    $PlainPassword.ToUpperInvariant().ToCharArray() |
        Where-Object { [char]::IsLetterOrDigit($_) }
)
if ($Effective.Length -lt 10) {
    throw 'The password must contain at least 10 letters or numbers.'
}

$Config = Get-Content -LiteralPath $ConfigPath -Raw | ConvertFrom-Json
$Config.pairing_key = $PlainPassword
$Temporary = Join-Path $ConfigDir 'config.json.new'
[System.IO.File]::WriteAllText(
    $Temporary,
    ($Config | ConvertTo-Json -Depth 8),
    [System.Text.UTF8Encoding]::new($false)
)
Move-Item -LiteralPath $Temporary -Destination $ConfigPath -Force

$Running = @(
    Get-CimInstance Win32_Process -Filter "Name='KIMQuestRemoteHost.exe'" -ErrorAction SilentlyContinue
)
foreach ($Process in $Running) {
    Stop-Process -Id $Process.ProcessId -Force -ErrorAction Stop
}
if (Test-Path -LiteralPath $TargetExe) {
    Start-Process -FilePath $TargetExe -WorkingDirectory $InstallDir
}

$PlainPassword = $null
$SecurePassword.Dispose()
Write-Host 'PAIRING_PASSWORD_UPDATED'
Write-Host "Effective letters/numbers: $($Effective.Length)"
Write-Host 'Case and punctuation are ignored for Meta Quest protocol compatibility.'
Write-Host 'Certificate and private key were preserved.'
