$ErrorActionPreference = "Continue"

Write-Host "=================================================="
Write-Host "Reset or Debug Hermes"
Write-Host "=================================================="
Write-Host ""
Write-Host "Choose:"
Write-Host "  1  Collect diagnostics"
Write-Host "  2  Reset Hermes config"
Write-Host ""
$choice = Read-Host "Type 1 or 2, then press Enter"

$scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$packRoot = Split-Path -Parent $scriptDir
$installRoot = Join-Path $env:LOCALAPPDATA "TongchengHermes"
$venvDir = Join-Path $installRoot "venv"
$pythonExe = Join-Path $venvDir "Scripts\python.exe"
$hermesExe = Join-Path $venvDir "Scripts\hermes.exe"
$hermesHome = Join-Path $env:USERPROFILE ".hermes"
$desktop = [Environment]::GetFolderPath("Desktop")
if ([string]::IsNullOrWhiteSpace($desktop)) { $desktop = $env:USERPROFILE }
$stamp = Get-Date -Format "yyyyMMdd_HHmmss"
$work = Join-Path $env:TEMP "HermesDiagnostics_$stamp"
$zip = Join-Path $desktop "HermesDiagnostics_$stamp.zip"

function Redact([string]$text) {
  if ($null -eq $text) { return "" }
  $t = $text
  $t = $t -replace "sk-tc_[A-Za-z0-9_\.-]+", "sk-tc_REDACTED"
  $t = $t -replace "(api_key:\s*)\S+", '$1REDACTED'
  $t = $t -replace "(OPENAI_API_KEY=).+", '$1REDACTED'
  return $t
}

function Write-Text([string]$path, [string]$text) {
  $dir = Split-Path -Parent $path
  if ($dir -and !(Test-Path $dir)) { New-Item -ItemType Directory -Path $dir -Force | Out-Null }
  $text | Set-Content -LiteralPath $path -Encoding UTF8
}

function Append-CommandOutput([string]$path, [string]$title, [scriptblock]$block) {
  Add-Content -LiteralPath $path -Encoding UTF8 -Value ""
  Add-Content -LiteralPath $path -Encoding UTF8 -Value "== $title =="
  try {
    $out = & $block 2>&1 | Out-String -Width 260
    Add-Content -LiteralPath $path -Encoding UTF8 -Value (Redact $out)
  } catch {
    Add-Content -LiteralPath $path -Encoding UTF8 -Value "FAILED: $($_.Exception.Message)"
  }
}

if ($choice -eq "2") {
  if (Test-Path $hermesHome) {
    $backup = "$hermesHome.backup_$stamp"
    Move-Item -LiteralPath $hermesHome -Destination $backup -Force
    Write-Host "Reset complete. Backup: $backup"
  } else {
    Write-Host "No Hermes config found."
  }
  Write-Host "Run 02_CONFIGURE_KEY.cmd again."
  exit 0
}

if (Test-Path $work) { Remove-Item -LiteralPath $work -Recurse -Force }
New-Item -ItemType Directory -Path $work -Force | Out-Null
$runtimeDir = Join-Path $work "runtime"
$configDir = Join-Path $work "config"
$logsDir = Join-Path $work "logs"
New-Item -ItemType Directory -Path $runtimeDir,$configDir,$logsDir -Force | Out-Null

$infoPath = Join-Path $runtimeDir "info.txt"
Write-Text $infoPath "Date: $(Get-Date -Format o)"
Add-Content -LiteralPath $infoPath -Encoding UTF8 -Value "User: $env:USERNAME"
Add-Content -LiteralPath $infoPath -Encoding UTF8 -Value "Computer: $env:COMPUTERNAME"
Add-Content -LiteralPath $infoPath -Encoding UTF8 -Value "PackRoot: $packRoot"
Add-Content -LiteralPath $infoPath -Encoding UTF8 -Value "InstallRoot: $installRoot"
Add-Content -LiteralPath $infoPath -Encoding UTF8 -Value "HermesHome: $hermesHome"
Add-Content -LiteralPath $infoPath -Encoding UTF8 -Value "PythonExeExists: $(Test-Path $pythonExe)"
Add-Content -LiteralPath $infoPath -Encoding UTF8 -Value "HermesExeExists: $(Test-Path $hermesExe)"
Add-Content -LiteralPath $infoPath -Encoding UTF8 -Value "ConfigExists: $(Test-Path (Join-Path $hermesHome 'config.yaml'))"
Add-Content -LiteralPath $infoPath -Encoding UTF8 -Value "EnvExists: $(Test-Path (Join-Path $hermesHome '.env'))"
Add-Content -LiteralPath $infoPath -Encoding UTF8 -Value "PowerShell: $($PSVersionTable.PSVersion)"
try {
  $os = Get-CimInstance Win32_OperatingSystem
  Add-Content -LiteralPath $infoPath -Encoding UTF8 -Value "OS: $($os.Caption) $($os.Version) $($os.OSArchitecture)"
} catch {}

$commandsPath = Join-Path $runtimeDir "commands.txt"
Write-Text $commandsPath "Hermes command checks"
if (Test-Path $pythonExe) {
  Append-CommandOutput $commandsPath "python --version" { & $pythonExe --version }
  Append-CommandOutput $commandsPath "pip list" { & $pythonExe -m pip list }
}
if (Test-Path $hermesExe) {
  Append-CommandOutput $commandsPath "hermes --help" { & $hermesExe --help }
}

$filesPath = Join-Path $runtimeDir "files.txt"
Write-Text $filesPath "InstallRoot files"
try {
  if (Test-Path $installRoot) {
    Get-ChildItem -LiteralPath $installRoot -Force -Recurse -ErrorAction SilentlyContinue |
      Select-Object FullName, Length, LastWriteTime |
      Format-Table -AutoSize | Out-String -Width 260 |
      Set-Content -LiteralPath $filesPath -Encoding UTF8
  } else {
    Add-Content -LiteralPath $filesPath -Encoding UTF8 -Value "Missing: $installRoot"
  }
} catch {
  Add-Content -LiteralPath $filesPath -Encoding UTF8 -Value "FAILED: $($_.Exception.Message)"
}

$configFiles = @("config.yaml", ".env")
foreach ($file in $configFiles) {
  $src = Join-Path $hermesHome $file
  if (Test-Path $src) {
    $content = Get-Content -LiteralPath $src -Raw -ErrorAction SilentlyContinue
    Write-Text (Join-Path $configDir ($file + ".redacted.txt")) (Redact $content)
  }
}

try {
  Get-Process -ErrorAction SilentlyContinue |
    Where-Object { $_.ProcessName -match "python|hermes" } |
    Select-Object ProcessName,Id,Path,StartTime |
    Format-List | Out-String -Width 260 |
    Set-Content (Join-Path $runtimeDir "processes.txt") -Encoding UTF8
} catch {
  Write-Text (Join-Path $runtimeDir "processes.txt") "FAILED: $($_.Exception.Message)"
}

try {
  if (Test-Path $zip) { Remove-Item -LiteralPath $zip -Force }
  Compress-Archive -Path (Join-Path $work "*") -DestinationPath $zip -Force
  Write-Host "Diagnostics saved to:"
  Write-Host "  $zip"
} catch {
  Write-Host "FAILED to create diagnostics zip: $($_.Exception.Message)"
  Write-Host "Raw diagnostics folder:"
  Write-Host "  $work"
  exit 1
}
