param(
  [string]$InstallScope = $(if ($env:KIWI_CONTROL_INSTALL_SCOPE) { $env:KIWI_CONTROL_INSTALL_SCOPE } else { "user" }),
  [string]$InstallRoot = $(if ($env:KIWI_CONTROL_INSTALL_ROOT) { $env:KIWI_CONTROL_INSTALL_ROOT } else { "" }),
  [string]$PathBin = $(if ($env:KIWI_CONTROL_PATH_BIN) { $env:KIWI_CONTROL_PATH_BIN } else { "" }),
  [string]$ResultPath = $(if ($env:KIWI_CONTROL_RESULT_PATH) { $env:KIWI_CONTROL_RESULT_PATH } else { "" }),
  [string]$PreferredNodePath = $(if ($env:KIWI_CONTROL_NODE_ABSOLUTE) { $env:KIWI_CONTROL_NODE_ABSOLUTE } elseif ($env:KIWI_CONTROL_NODE) { $env:KIWI_CONTROL_NODE } elseif ($env:SHREY_JUNIOR_NODE) { $env:SHREY_JUNIOR_NODE } else { "" })
)

$ErrorActionPreference = "Stop"
$BundleRoot = Split-Path -Parent $MyInvocation.MyCommand.Path
$GlobalHome = if ($InstallScope -eq "machine") {
  if ([string]::IsNullOrWhiteSpace($InstallRoot)) {
    Join-Path $env:ProgramData "Kiwi Control"
  } else {
    $InstallRoot
  }
} else {
  if ($env:KIWI_CONTROL_HOME) { $env:KIWI_CONTROL_HOME } else { Join-Path $HOME ".kiwi-control" }
}
$PathBin = if ([string]::IsNullOrWhiteSpace($PathBin)) { Join-Path $GlobalHome "bin" } else { $PathBin }
$InstallRoot = if ($InstallScope -eq "machine") {
  Join-Path $GlobalHome "cli\kiwi-control-0.2.0-beta.16"
} else {
  Join-Path $GlobalHome "releases\kiwi-control-0.2.0-beta.16"
}
$ReceiptPath = if ([string]::IsNullOrWhiteSpace($ResultPath)) { Join-Path $GlobalHome "desktop-cli-install.json" } else { $ResultPath }
$PreferredNode = if (-not [string]::IsNullOrWhiteSpace($PreferredNodePath)) { $PreferredNodePath } else { $null }

if (-not $PreferredNode -and -not (Get-Command node -ErrorAction SilentlyContinue)) {
  Write-Error "Kiwi Control CLI install error: Node.js 22+ is required for the beta CLI bundle."
  exit 1
}

New-Item -ItemType Directory -Force -Path (Split-Path -Parent $InstallRoot) | Out-Null
New-Item -ItemType Directory -Force -Path $PathBin | Out-Null

if (Test-Path $InstallRoot) {
  Remove-Item -Recurse -Force $InstallRoot
}

Copy-Item -Recurse -Force $BundleRoot $InstallRoot

$EscapedInstallRoot = $InstallRoot.Replace('"', '""')
$EscapedPreferredNode = if ($PreferredNode) { $PreferredNode.Replace('"', '""') } else { "" }
$Wrapper = @"
@echo off
setlocal
set "PREFERRED_NODE=$EscapedPreferredNode"
if not "%KIWI_CONTROL_NODE_ABSOLUTE%"=="" set "PREFERRED_NODE=%KIWI_CONTROL_NODE_ABSOLUTE%"
if not "%KIWI_CONTROL_NODE%"=="" set "PREFERRED_NODE=%KIWI_CONTROL_NODE%"
if not "%SHREY_JUNIOR_NODE%"=="" set "PREFERRED_NODE=%SHREY_JUNIOR_NODE%"
if defined PREFERRED_NODE (
  "%PREFERRED_NODE%" "$EscapedInstallRoot\lib\cli.js" %*
  exit /b %ERRORLEVEL%
)
node "$EscapedInstallRoot\lib\cli.js" %*
"@

Set-Content -Path (Join-Path $PathBin "kiwi-control.cmd") -Value $Wrapper -NoNewline
Set-Content -Path (Join-Path $PathBin "kc.cmd") -Value $Wrapper -NoNewline

$PathChanged = $false
$VerificationStatus = "failed"
$VerificationDetail = ""
$VerificationCommandPath = $null
$RequiresNewTerminal = $false
if ($InstallScope -eq "machine") {
  $MachinePath = [Environment]::GetEnvironmentVariable("Path", "Machine")
  $PathEntries = if ($MachinePath) { $MachinePath -split ';' | Where-Object { $_ } } else { @() }
  if ($PathEntries -notcontains $PathBin) {
    $NewMachinePath = if ($MachinePath) { "$PathBin;$MachinePath" } else { $PathBin }
    [Environment]::SetEnvironmentVariable("Path", $NewMachinePath, "Machine")
    $PathChanged = $true
    $PathUpdateMessage = "Machine PATH updated for future terminals."
  } else {
    $PathUpdateMessage = "Machine PATH already includes $PathBin"
  }
  $Detail = "Kiwi Control terminal commands installed system-wide."
} else {
  $CurrentUserPath = [Environment]::GetEnvironmentVariable("Path", "User")
  $PathEntries = if ($CurrentUserPath) { $CurrentUserPath -split ';' | Where-Object { $_ } } else { @() }
  if ($PathEntries -notcontains $PathBin) {
    $NewUserPath = if ($CurrentUserPath) { "$PathBin;$CurrentUserPath" } else { $PathBin }
    [Environment]::SetEnvironmentVariable("Path", $NewUserPath, "User")
    $PathChanged = $true
    $PathUpdateMessage = "PATH updated for future terminals."
  } else {
    $PathUpdateMessage = "PATH already includes $PathBin"
  }
  $Detail = "Kiwi Control CLI installed."
}

$VerificationScript = '$machine = [Environment]::GetEnvironmentVariable(''Path'', ''Machine''); ' +
  '$user = [Environment]::GetEnvironmentVariable(''Path'', ''User''); ' +
	  '$env:Path = @($machine, $user) -join '';''; ' +
	  '$command = Get-Command kc -ErrorAction Stop; ' +
	  '$commandPath = $command.Source; ' +
	  '& $commandPath --help | Out-Null; ' +
	  'Write-Output $commandPath'

try {
  $VerificationOutput = & powershell.exe -NoProfile -Command $VerificationScript 2>&1 | Out-String
  if ($LASTEXITCODE -eq 0) {
    $ResolvedCommandPath = ($VerificationOutput.Trim() -split "\r?\n" | Select-Object -Last 1)
    $VerificationStatus = "passed"
    $VerificationCommandPath = if ([string]::IsNullOrWhiteSpace($ResolvedCommandPath)) { Join-Path $PathBin "kc.cmd" } else { $ResolvedCommandPath }
    $RequiresNewTerminal = $PathChanged
    $VerificationDetail = if ($InstallScope -eq "machine") {
      if ($PathChanged) {
        "Terminal commands are enabled system-wide. Open a new terminal to use kc."
      } else {
        "Terminal commands are already enabled system-wide."
      }
    } elseif ($PathChanged) {
      "Terminal commands are enabled for this user. Open a new terminal to use kc."
    } else {
      "Terminal commands are already enabled for this user."
    }
  } else {
    $VerificationDetail = $VerificationOutput.Trim()
  }
} catch {
  $VerificationDetail = $_.Exception.Message
}

Write-Host $Detail
Write-Host "Primary command: $PathBin\kiwi-control.cmd"
Write-Host "Short alias: $PathBin\kc.cmd"
Write-Host $PathUpdateMessage
Write-Host $VerificationDetail
if ($RequiresNewTerminal) {
  Write-Host "Next step: open a new terminal window."
}

if (-not [string]::IsNullOrWhiteSpace($ReceiptPath)) {
  $payload = @{
    installScope = $InstallScope
    installRoot = $InstallRoot
    installBinDir = $PathBin
    pathChanged = $PathChanged
    detail = $Detail
    installedCommandPath = Join-Path $PathBin "kc.cmd"
    verificationStatus = $VerificationStatus
    verificationDetail = $VerificationDetail
    verificationCommandPath = $VerificationCommandPath
    requiresNewTerminal = $RequiresNewTerminal
    updatedAt = (Get-Date).ToString("o")
  } | ConvertTo-Json -Depth 5
  New-Item -ItemType Directory -Force -Path (Split-Path -Parent $ReceiptPath) | Out-Null
  Set-Content -Path $ReceiptPath -Value $payload
}

if ($VerificationStatus -ne "passed") {
  if ([string]::IsNullOrWhiteSpace($VerificationDetail)) {
    Write-Error "Kiwi could not verify kc from a fresh shell after installation."
  } else {
    Write-Error $VerificationDetail
  }
  exit 1
}
