# Install the ExcelRewind Companion for the current user.
# - Copies the exe to %LOCALAPPDATA%\ExcelRewind
# - Creates a Start-Menu shortcut
# - Optional: adds an HKCU Run key so it starts at login (-AutoStart)
#
# Usage:
#   .\install-companion.ps1              # install + Start-Menu shortcut
#   .\install-companion.ps1 -AutoStart   # also start at login
#   .\install-companion.ps1 -Uninstall   # remove everything this script created
param(
    [switch]$AutoStart,
    [switch]$Uninstall
)
$ErrorActionPreference = "Stop"
$installDir = Join-Path $env:LOCALAPPDATA "ExcelRewind"
$exeName = "ExcelRewindCompanion.exe"
$destExe = Join-Path $installDir $exeName
$startMenu = Join-Path $env:APPDATA "Microsoft\Windows\Start Menu\Programs"
$shortcut = Join-Path $startMenu "ExcelRewind Companion.lnk"
$runKey = "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run"
$runValue = "ExcelRewindCompanion"

if ($Uninstall) {
    if (Test-Path $shortcut) { Remove-Item $shortcut -Force }
    try { Remove-ItemProperty -Path $runKey -Name $runValue -ErrorAction Stop } catch {}
    if (Test-Path $destExe) { Remove-Item $destExe -Force }
    Write-Host "Uninstalled ExcelRewind Companion (per-user)."
    return
}

$srcExe = Join-Path $PSScriptRoot $exeName
if (-not (Test-Path $srcExe)) { throw "Missing $exeName next to this script." }

New-Item -ItemType Directory -Force -Path $installDir | Out-Null
Copy-Item $srcExe $destExe -Force
Write-Host "Installed to $destExe"

# Start-Menu shortcut
$ws = New-Object -ComObject WScript.Shell
$lnk = $ws.CreateShortcut($shortcut)
$lnk.TargetPath = $destExe
$lnk.WorkingDirectory = $installDir
$lnk.Description = "ExcelRewind Companion (cross-workbook capture helper)"
$lnk.Save()
Write-Host "Start-Menu shortcut created."

if ($AutoStart) {
    New-ItemProperty -Path $runKey -Name $runValue -Value "`"$destExe`"" -PropertyType String -Force | Out-Null
    Write-Host "Auto-start at login enabled."
}

# Launch now (attaches to Excel only if it is already running; never starts Excel).
Start-Process $destExe
Write-Host "Companion started."
