# Install the AdBlock-Maxxer YouTube companion to auto-start (hidden) at Windows login.
# Uses pythonw.exe (no console window) + a Startup-folder shortcut - no admin required.
$ErrorActionPreference = "Stop"

$root = Split-Path $PSScriptRoot -Parent

# Prefer the standalone exe (no Python needed). The companion now ships as a --onedir
# FOLDER (abm-companion\abm-companion.exe + _internal\), so look for the exe inside that
# folder first; keep the old flat paths for backward-compat with onefile installs.
$exe = $null
foreach ($cand in @(
    # onedir layout (current): folder extracted next to the scripts or under companion\
    (Join-Path $PSScriptRoot "abm-companion\abm-companion.exe"),
    (Join-Path $root "companion\abm-companion\abm-companion.exe"),
    (Join-Path $root "companion\exe-dist\abm-companion\abm-companion.exe"),
    # legacy onefile layout
    (Join-Path $PSScriptRoot "abm-companion.exe"),
    (Join-Path $root "companion\abm-companion.exe"),
    (Join-Path $root "companion\exe-dist\abm-companion.exe"))) {
  if (Test-Path $cand) { $exe = $cand; break }
}
# Last resort: the user may have unzipped the companion folder somewhere nearby -- find it.
if (-not $exe) {
  foreach ($searchRoot in @($PSScriptRoot, $root)) {
    $hit = Get-ChildItem -Path $searchRoot -Filter "abm-companion.exe" -Recurse -ErrorAction SilentlyContinue |
           Select-Object -First 1
    if ($hit) { $exe = $hit.FullName; break }
  }
}

if ($exe) {
  $target  = $exe
  $args    = ""
  $workdir = Split-Path $exe
  Write-Host "Using standalone exe: $exe"
} else {
  # Fall back to pythonw + the .py script
  $script = Join-Path $root "companion\abm_companion.py"
  if (-not (Test-Path $script)) { throw "neither abm-companion.exe nor abm_companion.py found" }
  $pw = (Get-Command pythonw.exe -ErrorAction SilentlyContinue).Source
  if (-not $pw) {
    $py = (Get-Command python.exe -ErrorAction SilentlyContinue).Source
    if ($py) { $pw = Join-Path (Split-Path $py) "pythonw.exe" }
  }
  if (-not $pw -or -not (Test-Path $pw)) { throw "no exe and pythonw.exe not found - install Python or use abm-companion.exe" }
  $target  = $pw
  $args    = '"{0}"' -f $script
  $workdir = Split-Path $script
  Write-Host "Using python: $pw $script"
}

$startup = [Environment]::GetFolderPath("Startup")
$lnk     = Join-Path $startup "AdBlock-Maxxer YouTube Companion.lnk"

$ws = New-Object -ComObject WScript.Shell
$s  = $ws.CreateShortcut($lnk)
$s.TargetPath       = $target
$s.Arguments        = $args
$s.WorkingDirectory = $workdir
$s.WindowStyle      = 7   # minimized (windowless regardless)
$s.Description      = "AdBlock-Maxxer YouTube ad-free companion"
$s.Save()
Write-Host "Startup shortcut installed: $lnk"

# Retire any companion that's already running (an old build's exe, or a dev pythonw) so OUR
# build becomes the live server. This is what makes a version cutover clean WITHOUT the user
# stopping anything by hand. (The companion also re-registers the native host on startup, so
# the browser will launch this build from now on.)
Get-CimInstance Win32_Process -Filter "Name='abm-companion.exe'" -ErrorAction SilentlyContinue |
  ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue; Write-Host ("Stopped old companion exe pid " + $_.ProcessId) }
Get-CimInstance Win32_Process -Filter "Name='pythonw.exe'" -ErrorAction SilentlyContinue |
  Where-Object { $_.CommandLine -like "*abm_companion.py*" } |
  ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue; Write-Host ("Stopped dev companion pid " + $_.ProcessId) }
Start-Sleep -Milliseconds 600

if ($args) { Start-Process -FilePath $target -ArgumentList $args -WorkingDirectory $workdir -WindowStyle Hidden }
else { Start-Process -FilePath $target -WorkingDirectory $workdir -WindowStyle Hidden }
Start-Sleep -Seconds 2
$ok = $false
try { $c = New-Object Net.Sockets.TcpClient; $c.Connect("127.0.0.1", 47823); $ok = $true; $c.Close() } catch {}
Write-Host ("Launched hidden companion now: " + ($(if ($ok) { "serving on 127.0.0.1:47823" } else { "(starting...)" })))
Write-Host "Done. The companion will now start automatically and invisibly every time you log in."
