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

$ErrorActionPreference = 'Stop'
$TargetExe = Join-Path ([System.IO.Path]::GetFullPath($InstallDir)) 'KIMQuestRemoteHost.exe'
if (-not (Test-Path -LiteralPath $TargetExe)) {
    throw "Installed EXE not found: $TargetExe"
}
$ActualVersion = (& $TargetExe --version).Trim()
if ($ActualVersion -ne $ExpectedVersion) {
    throw "Version mismatch. Expected $ExpectedVersion, got $ActualVersion"
}
$Listener = Get-NetTCPConnection -LocalPort 45830 -State Listen -ErrorAction SilentlyContinue
if (-not $Listener) {
    throw 'TCP 45830 is not listening.'
}
$Rule = Get-NetFirewallRule -DisplayName 'KIM Quest Remote Host' -ErrorAction Stop
$Remote = @($Rule | Get-NetFirewallAddressFilter).RemoteAddress
$HasTailscaleScope = (
    '100.64.0.0/10' -in $Remote -or
    '100.64.0.0/255.192.0.0' -in $Remote
)
if ('LocalSubnet' -notin $Remote -or -not $HasTailscaleScope) {
    throw "Firewall remote scope is not hardened: $($Remote -join ', ')"
}
$PatchTaskName = 'KIM Remote Auto Patcher'
$PatchTask = Get-ScheduledTask -TaskName $PatchTaskName -ErrorAction SilentlyContinue
if (-not $PatchTask) {
    throw "Signed patcher scheduled task not found: $PatchTaskName"
}
if ($PatchTask.State -eq 'Disabled') {
    throw "Signed patcher scheduled task is disabled: $PatchTaskName"
}
$ConfigDir = Join-Path $env:LOCALAPPDATA 'KIMQuestRemote'
foreach ($Name in @('config.json', 'host-cert.pem', 'host-key.pem')) {
    if (-not (Test-Path -LiteralPath (Join-Path $ConfigDir $Name))) {
        throw "Local identity file is missing: $Name"
    }
}

Write-Host 'VERIFY_INSTALL_PASS'
Write-Host "Version: $ActualVersion"
Write-Host "Listener: TCP 45830 (PID $(@($Listener.OwningProcess) -join ','))"
Write-Host "Firewall: $($Remote -join ', ')"
Write-Host "Startup patcher: $PatchTaskName ($($PatchTask.State))"
Write-Host 'Open KIM Remote from the desktop to view the local address and pairing key.'
