param(
    [string]$InstallDirectory = (Join-Path $env:LOCALAPPDATA "Programs\ImageAnywhereAgent"),
    [switch]$Force
)

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

$packageRoot = Split-Path -Path $PSScriptRoot -Parent
$agentSource = Join-Path $packageRoot "agent"
if (-not (Test-Path -Path (Join-Path $agentSource "IAUWP.Agent.exe"))) {
    throw "This script must be run from an extracted ImageAnywhere Agent field package."
}

$resolvedInstallDirectory = $InstallDirectory
if (Test-Path -Path $resolvedInstallDirectory) {
    if (-not $Force.IsPresent) {
        throw "Install directory '$resolvedInstallDirectory' already exists. Re-run with -Force to replace package files."
    }
}
else {
    New-Item -ItemType Directory -Path $resolvedInstallDirectory -Force | Out-Null
}

Copy-Item -Path (Join-Path $packageRoot "*") -Destination $resolvedInstallDirectory -Recurse -Force

$installRecord = [pscustomobject]@{
    InstalledAt = (Get-Date).ToString("O")
    InstallDirectory = $resolvedInstallDirectory
    AgentExe = Join-Path $resolvedInstallDirectory "agent\IAUWP.Agent.exe"
    StartupConfigured = $false
    Notes = "Per-user install only. This script does not create a service, scheduled task, Run key, or silent startup behavior."
}
$installRecord | ConvertTo-Json -Depth 4 | Set-Content -Path (Join-Path $resolvedInstallDirectory "install-location.json") -Encoding UTF8

Write-Host "ImageAnywhere Agent package installed to $resolvedInstallDirectory"
Write-Host "The agent is not running yet and no startup behavior was configured."
Write-Host "Run scripts\Start-Agent.ps1 from the install directory to opt in for this user session."
