param(
    [string]$InstallDirectory = (Split-Path -Path $PSScriptRoot -Parent),
    [string]$AgentArguments = ""
)

Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"

$agentExe = Join-Path $InstallDirectory "agent\IAUWP.Agent.exe"
if (-not (Test-Path -Path $agentExe)) {
    throw "Agent executable was not found at '$agentExe'."
}

$runDirectory = Join-Path $InstallDirectory "run"
New-Item -ItemType Directory -Path $runDirectory -Force | Out-Null
$pidPath = Join-Path $runDirectory "agent.pid"

if (Test-Path -Path $pidPath) {
    $existingPid = Get-Content -Path $pidPath -Raw
    if ($existingPid -match '^\s*\d+\s*$') {
        $existingProcess = Get-Process -Id ([int]$existingPid) -ErrorAction SilentlyContinue
        if ($existingProcess) {
            throw "Agent appears to already be running with PID $existingPid. Run Status-Agent.ps1 or Stop-Agent.ps1 first."
        }
    }
}

$startProcessArgs = @{
    FilePath = $agentExe
    WorkingDirectory = (Split-Path -Path $agentExe -Parent)
    WindowStyle = "Hidden"
    PassThru = $true
}

if (-not [string]::IsNullOrWhiteSpace($AgentArguments)) {
    $startProcessArgs.ArgumentList = $AgentArguments
}

$process = Start-Process @startProcessArgs

$process.Id | Set-Content -Path $pidPath -Encoding ASCII

Write-Host "ImageAnywhere Agent started with PID $($process.Id)."
Write-Host "This is an opt-in user-session process. It is not configured to restart after sign-out or reboot."
