<#
  adom-native-browser :: Windows install (managed machine / golden-image bake)
  --------------------------------------------------------------------------------
  Registers the three pieces. Run OUTSIDE Claude Code (the %LOCALAPPDATA%\Adom Bridge path is
  AppContainer/wcifs-virtualized for Claude-spawned tools — see Bridge/CLAUDE.md). From a
  Claude session, do the bridges-cache copy via WSL2 `cp` or `adom-bridge-cli shell_execute` instead.

  Usage:
    powershell -ExecutionPolicy Bypass -File install.ps1 -ExtensionId <id> [-Edge]
#>
param(
  [Parameter(Mandatory = $true)][string]$ExtensionId,
  [switch]$Edge,                 # also register for Edge (default registers Chrome)
  [string]$UpdateXmlUrl = ""     # self-hosted .crx update manifest URL (force-install)
)

$ErrorActionPreference = 'Stop'
$repo   = Split-Path -Parent $PSScriptRoot
$hostJs = Join-Path $repo 'host\native-host.bat'
$HostName = 'inc.adom.native_browser'

# 1) Bridge -> ab bridges-cache  (auto-discovered by Bridge's registry)
$cache = Join-Path $env:LOCALAPPDATA 'Adom Bridge\bridges-cache\native-browser'
New-Item -ItemType Directory -Force -Path $cache | Out-Null
Copy-Item -Recurse -Force (Join-Path $repo 'bridge\*') $cache
Write-Host "bridge -> $cache"

# 2) Native-messaging host manifest (rendered from template) + HKCU registration (no UAC)
$manifest = @{
  name           = $HostName
  description    = 'Adom native-browser bridge host (stdio <-> Bridge)'
  path           = $hostJs
  type           = 'stdio'
  allowed_origins = @("chrome-extension://$ExtensionId/")
} | ConvertTo-Json -Depth 5
$manifestPath = Join-Path $repo 'host\host-manifest.json'
$manifest | Set-Content -Path $manifestPath -Encoding utf8
Write-Host "host manifest -> $manifestPath"

function Register-Host($vendorKey) {
  $key = "HKCU:\Software\$vendorKey\NativeMessagingHosts\$HostName"
  New-Item -Path $key -Force | Out-Null
  Set-ItemProperty -Path $key -Name '(default)' -Value $manifestPath
  Write-Host "registered $key"
}
Register-Host 'Google\Chrome'
if ($Edge) { Register-Host 'Microsoft\Edge' }

# 3) Force-install policy (managed browsers) — HKLM, needs elevation
if ($UpdateXmlUrl -ne "") {
  function Force-Install($policyRoot) {
    New-Item -Path $policyRoot -Force | Out-Null
    Set-ItemProperty -Path $policyRoot -Name '1' -Value "$ExtensionId;$UpdateXmlUrl"
    Write-Host "force-install -> $policyRoot"
  }
  Force-Install 'HKLM:\SOFTWARE\Policies\Google\Chrome\ExtensionInstallForcelist'
  if ($Edge) { Force-Install 'HKLM:\SOFTWARE\Policies\Microsoft\Edge\ExtensionInstallForcelist' }
}

Write-Host "done. Restart the browser; the extension popup should show 'Connected to Bridge'."
