$ErrorActionPreference = "Continue"

$Root = "C:\UniDesk\personal-wechat"
$WcfRoot = Join-Path $Root "wcf\v39.5.2"
$PythonSite = Join-Path $WcfRoot "python-site"
$StateRoot = Join-Path $Root "wcf-state"
$DataRoot = Join-Path $Root "data\profile"
$PidFile = Join-Path $StateRoot "wcf-host.pid"
$StatusFile = Join-Path $StateRoot "status.json"
$PrepareResultFile = Join-Path $StateRoot "prepare-result.json"
$PrepareStdout = Join-Path $StateRoot "prepare.stdout.log"
$PrepareStderr = Join-Path $StateRoot "prepare.stderr.log"
$PrepareProgress = Join-Path $StateRoot "prepare-progress.log"
$Stdout = Join-Path $StateRoot "wcf-host.stdout.log"
$Stderr = Join-Path $StateRoot "wcf-host.stderr.log"
$HostLog = Join-Path $StateRoot "wcf-host.log"
$InjectorLog = Join-Path $WcfRoot "injector.log"

function Read-JsonFile {
  param([string]$Path)
  if (!(Test-Path -LiteralPath $Path)) { return $null }
  try { return Get-Content $Path -Raw | ConvertFrom-Json } catch { return @{ parseError = $_.Exception.Message } }
}

function Tail-Text {
  param([string]$Path)
  if (!(Test-Path -LiteralPath $Path)) { return "" }
  try {
    return (Get-Content $Path -Tail 80 -ErrorAction SilentlyContinue) -join "`n"
  } catch {
    return $_.Exception.Message
  }
}

$pidValue = $null
$running = $false
if (Test-Path -LiteralPath $PidFile) {
  $pidValue = (Get-Content $PidFile -ErrorAction SilentlyContinue | Select-Object -First 1)
  if ($pidValue) {
    $running = [bool](Get-Process -Id ([int]$pidValue) -ErrorAction SilentlyContinue)
  }
}

$status = Read-JsonFile $StatusFile
$prepare = Read-JsonFile $PrepareResultFile
$ports = Get-NetTCPConnection -LocalPort 10086,10087 -ErrorAction SilentlyContinue | Select-Object LocalAddress,LocalPort,State,OwningProcess
$personalProcesses = Get-CimInstance Win32_Process -ErrorAction SilentlyContinue |
  Where-Object {
    ($_.ExecutablePath -like "$Root\*") -or
    ($_.CommandLine -like "*$WcfRoot\wcf_host.py*") -or
    ($_.Name -eq "WeChatAppEx.exe" -and $_.CommandLine -like "*$DataRoot*")
  } |
  Select-Object ProcessId,ParentProcessId,Name,ExecutablePath,CommandLine

[pscustomobject]@{
  ok = $true
  pid = $pidValue
  running = $running
  prepared = if ($prepare) { [bool]$prepare.ok } else { $false }
  prepare = $prepare
  prepareRuntime = [ordered]@{
    stdout = $PrepareStdout
    stderr = $PrepareStderr
    progress = $PrepareProgress
    stdoutTail = Tail-Text $PrepareStdout
    stderrTail = Tail-Text $PrepareStderr
    progressTail = Tail-Text $PrepareProgress
  }
  status = $status
  ports = $ports
  personalProcesses = $personalProcesses
  logs = [ordered]@{
    stdout = $Stdout
    stderr = $Stderr
    host = $HostLog
    injector = $InjectorLog
    stdoutTail = Tail-Text $Stdout
    stderrTail = Tail-Text $Stderr
    hostTail = Tail-Text $HostLog
    injectorTail = Tail-Text $InjectorLog
  }
  paths = [ordered]@{
    root = $Root
    dataRoot = $DataRoot
    pythonSite = $PythonSite
    stateRoot = $StateRoot
    statusFile = $StatusFile
    prepareResultFile = $PrepareResultFile
  }
} | ConvertTo-Json -Depth 10
