$ErrorActionPreference='Continue'
$root=Split-Path -Parent (Split-Path -Parent $MyInvocation.MyCommand.Path)
$results=@()
function Add-Result($name,$ok,$detail){$script:results += [pscustomobject]@{Test=$name;Pass=[bool]$ok;Detail=$detail}}
$py=Join-Path $root 'Runtime\Python\python.exe'
$ahk=Join-Path $root 'Runtime\AutoHotkey\v2\AutoHotkey64.exe'
Add-Result 'Python runtime' (Test-Path $py) $py
Add-Result 'AutoHotkey runtime' (Test-Path $ahk) $ahk
if(Test-Path $py){
  $v=& $py --version 2>&1; Add-Result 'Python starts' ($LASTEXITCODE -eq 0) "$v"
  & $py -c "import pypdf; print(pypdf.__version__)" 2>&1 | Out-String | ForEach-Object {Add-Result 'PDF support' ($LASTEXITCODE -eq 0) $_.Trim()}
  & $py -m unittest discover -s (Join-Path $root 'ClinicalReasoningDatabase\research\tests') 2>&1 | Out-String | ForEach-Object {Add-Result 'Research engine tests' ($LASTEXITCODE -eq 0) $_.Trim()}
}
if(Test-Path $ahk){
  & $ahk /Validate (Join-Path $root 'App\PhUCKIT.ahk') 2>&1 | Out-String | ForEach-Object {Add-Result 'PhUCKIT AHK validation' ($LASTEXITCODE -eq 0) $_.Trim()}
}
foreach($url in @('https://rxnav.nlm.nih.gov','https://dailymed.nlm.nih.gov','https://api.fda.gov','https://eutils.ncbi.nlm.nih.gov')){
  try{$r=Invoke-WebRequest -UseBasicParsing -Method Head -TimeoutSec 15 -Uri $url; Add-Result "Network $url" ($r.StatusCode -lt 500) "HTTP $($r.StatusCode)"}catch{Add-Result "Network $url" $false $_.Exception.Message}
}
$results | Format-Table -AutoSize
$log=Join-Path $root ('Logs\Diagnostics-'+(Get-Date -Format 'yyyyMMdd-HHmmss')+'.json')
$results | ConvertTo-Json -Depth 4 | Set-Content $log -Encoding UTF8
Write-Host "Diagnostic report: $log"
if(($results|Where-Object{-not $_.Pass}).Count -gt 0){exit 1}else{exit 0}
