param(
  [switch]$Quiet
)
$ErrorActionPreference = "Stop"
$ScriptRoot = Split-Path -Parent $MyInvocation.MyCommand.Path
$InstallDir = Join-Path $env:LOCALAPPDATA "rtsp-web-player"
$ExtensionDir = Join-Path $InstallDir "extension"
$NativeBin = Join-Path $InstallDir "rtsp-web-native.exe"
$HostName = "com.rtspweb.player"
$ExtensionId = "giegomfhcmgebjhdiihnjohoinkbcjbh"

New-Item -ItemType Directory -Force -Path $InstallDir | Out-Null
if (Test-Path $ExtensionDir) {
  Remove-Item -Recurse -Force $ExtensionDir
}
Copy-Item -Recurse -Force (Join-Path $ScriptRoot "extension") $ExtensionDir
Copy-Item -Force (Join-Path $ScriptRoot "native\rtsp-web-native-windows-amd64.exe") $NativeBin

try {
  Set-Clipboard -Value $ExtensionDir
  Write-Host "Extension directory copied to clipboard:"
} catch {
  Write-Host "Extension directory:"
}
Write-Host $ExtensionDir
Write-Host ""
Write-Host "Fixed Chrome extension ID:"
Write-Host $ExtensionId
Write-Host ""

$ManifestPath = Join-Path $InstallDir "$HostName.json"
$Manifest = @{
  name = $HostName
  description = "RTSP Web Player Go Native Host"
  path = $NativeBin
  type = "stdio"
  allowed_origins = @("chrome-extension://$ExtensionId/")
} | ConvertTo-Json -Depth 5
Set-Content -Path $ManifestPath -Value $Manifest -Encoding ASCII

$RegKey = "HKCU\Software\Google\Chrome\NativeMessagingHosts\$HostName"
reg add $RegKey /ve /t REG_SZ /d $ManifestPath /f | Out-Null

Write-Host ""
Write-Host "Installed Native Messaging Host: $ManifestPath"
Write-Host "Allowed extension: chrome-extension://$ExtensionId/"
Write-Host ""
Write-Host "Chrome will open now."
Write-Host "Enable Developer mode, click Load unpacked, and paste/select the extension directory above."

$ProgramFilesX86 = [Environment]::GetEnvironmentVariable("ProgramFiles(x86)")
$ChromeCandidates = @(
  "$env:ProgramFiles\Google\Chrome\Application\chrome.exe",
  "$ProgramFilesX86\Google\Chrome\Application\chrome.exe",
  "$env:LOCALAPPDATA\Google\Chrome\Application\chrome.exe"
)
$Chrome = $ChromeCandidates | Where-Object { Test-Path $_ } | Select-Object -First 1
if ($Chrome) {
  Start-Process $Chrome "chrome://extensions"
} else {
  Start-Process "chrome://extensions"
}
Start-Process "https://rtsp.flyfish.dev/#demo"
Write-Host "Done."
