$ErrorActionPreference = "Stop"
$AppDir = Split-Path -Parent (Split-Path -Parent $MyInvocation.MyCommand.Path)
$EnvFile = Join-Path $AppDir "config\agent.env"
$Exe = Join-Path $AppDir "bin\controlcmd-agent.exe"
$LogDir = Join-Path $AppDir "logs"
$BootLog = Join-Path $LogDir "agent.boot.log"

New-Item -ItemType Directory -Force -Path $LogDir | Out-Null
Add-Content -Path $BootLog -Value "$(Get-Date -Format o) run-agent starting session_id=$([System.Diagnostics.Process]::GetCurrentProcess().SessionId) exe=$Exe env=$EnvFile"

if (!(Test-Path $EnvFile)) {
  Add-Content -Path $BootLog -Value "$(Get-Date -Format o) missing env file: $EnvFile"
  throw "Missing config file: $EnvFile. Copy config\agent.env.example to config\agent.env and edit it first."
}
if (!(Test-Path $Exe)) {
  Add-Content -Path $BootLog -Value "$(Get-Date -Format o) missing executable: $Exe"
  throw "Missing executable: $Exe"
}

Get-Content $EnvFile | ForEach-Object {
  $Line = $_.Trim()
  if ($Line -eq "" -or $Line.StartsWith("#")) { return }
  $Parts = $Line.Split("=", 2)
  if ($Parts.Length -eq 2) {
    [Environment]::SetEnvironmentVariable($Parts[0].Trim(), $Parts[1].Trim(), "Process")
  }
}

Add-Content -Path $BootLog -Value "$(Get-Date -Format o) launching agent server=$env:SERVER_URL device=$env:AGENT_DEVICE_NAME p2p=$env:AGENT_ENABLE_REMOTE_TERMINAL_P2P shell=$env:TERMINAL_SHELL"
& $Exe
$ExitCode = $LASTEXITCODE
Add-Content -Path $BootLog -Value "$(Get-Date -Format o) agent exited code=$ExitCode"
exit $ExitCode
