$ErrorActionPreference = "Stop"
$AppDir = Split-Path -Parent (Split-Path -Parent $MyInvocation.MyCommand.Path)
$RunDir = Join-Path $AppDir "run"
$LogDir = Join-Path $AppDir "logs"
$PidFile = Join-Path $RunDir "agent.pid"
$RunScript = Join-Path $AppDir "scripts\run-agent.ps1"
$StdoutLog = Join-Path $LogDir "agent.out.log"
$StderrLog = Join-Path $LogDir "agent.err.log"

New-Item -ItemType Directory -Force -Path $RunDir, $LogDir | Out-Null
if ([System.Diagnostics.Process]::GetCurrentProcess().SessionId -eq 0) {
  Write-Host "Warning: current process is running in Windows Session 0."
  Write-Host "Mobile terminal output requires the logged-in desktop session."
  Write-Host "Run this script from the Windows desktop user, or install the interactive logon task."
}
if (Test-Path $PidFile) {
  $ExistingPid = Get-Content $PidFile -ErrorAction SilentlyContinue
  if ($ExistingPid -and (Get-Process -Id $ExistingPid -ErrorAction SilentlyContinue)) {
    Write-Host "Agent is already running. PID=$ExistingPid"
    exit 0
  }
  Remove-Item $PidFile -Force -ErrorAction SilentlyContinue
}

$Process = Start-Process powershell.exe `
  -ArgumentList "-NoProfile -ExecutionPolicy Bypass -File `"$RunScript`"" `
  -RedirectStandardOutput $StdoutLog `
  -RedirectStandardError $StderrLog `
  -WindowStyle Hidden `
  -PassThru
$Process.Id | Set-Content $PidFile
Write-Host "Agent started. PID=$($Process.Id)"
Write-Host "Log: $StdoutLog"
Write-Host "Error log: $StderrLog"
