# RefDrop Windows Installer
# Registers the NativeMessaging host so Chrome can communicate with the helper app.
# Run as Administrator (or the registry key will go to HKCU which is fine for single-user).

param(
    [string]$ExtensionId = "obimncghooebncelfoommfdlamciclam"
)

$ErrorActionPreference = "Stop"

$InstallDir   = "$env:LOCALAPPDATA\RefDrop"
$HelperDir    = "$InstallDir\refdrop_helper"
$ExePath      = "$HelperDir\refdrop_helper.exe"
$ManifestPath = "$InstallDir\refdrop.json"
$RegKey       = "HKCU:\Software\Google\Chrome\NativeMessagingHosts\com.refdrop.helper"

Write-Host "  [1/3] Copying helper app..." -ForegroundColor Gray

# 1. Create install directory
New-Item -ItemType Directory -Force -Path $InstallDir | Out-Null

# 2. Copy helper folder
$ScriptDir  = Split-Path -Parent $MyInvocation.MyCommand.Path
$SourceDir  = Join-Path $ScriptDir "refdrop_helper"
if (-Not (Test-Path $SourceDir)) {
    Write-Error "refdrop_helper folder not found next to install.ps1"
    exit 1
}
Copy-Item $SourceDir $HelperDir -Recurse -Force
Write-Host "  [1/3] Done" -ForegroundColor Green

# 3. Write NativeMessaging manifest
Write-Host "  [2/3] Registering with Chrome..." -ForegroundColor Gray
$manifest = @{
    name            = "com.refdrop.helper"
    description     = "RefDrop Helper - bridges Chrome to PureRef"
    path            = $ExePath
    type            = "stdio"
    allowed_origins = @("chrome-extension://$ExtensionId/")
} | ConvertTo-Json -Depth 5

$manifest | Set-Content -Encoding UTF8 -Path $ManifestPath

# 4. Register in Chrome NativeMessaging registry
New-Item -Path $RegKey -Force | Out-Null
Set-ItemProperty -Path $RegKey -Name "(Default)" -Value $ManifestPath
Write-Host "  [2/3] Done" -ForegroundColor Green

Write-Host "  [3/3] Verifying installation..." -ForegroundColor Gray
if ((Test-Path $ExePath) -and (Test-Path $ManifestPath)) {
    Write-Host "  [3/3] All good!" -ForegroundColor Green
} else {
    Write-Error "Verification failed — some files are missing."
    exit 1
}
