param(
  [switch]$NoInstall,
  [switch]$NoShortcut
)

$ErrorActionPreference = 'Stop'
[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new()
$root = $PSScriptRoot
$shortcutName = 'S-Live.lnk'
$desktopPath = [Environment]::GetFolderPath('Desktop')
if (-not $desktopPath) { $desktopPath = Join-Path $env:USERPROFILE 'Desktop' }
$launcherPath = Join-Path $root 'scripts\launch_hidden.vbs'
$sourceIconPath = Join-Path $root 'public\sanglive.ico'
$shortcutIconDir = Join-Path $root '.runtime\shortcut-icons'
$shortcutIconPath = $null

function Assert-Node {
  $node = Get-Command node -ErrorAction SilentlyContinue
  if (-not $node) {
    throw 'Node.js is not installed. Install Node.js 20 LTS first: https://nodejs.org/'
  }
}

function Initialize-ShortcutIcon {
  if (-not (Test-Path $sourceIconPath)) { return $null }

  $hash = (Get-FileHash -LiteralPath $sourceIconPath -Algorithm SHA256).Hash.Substring(0, 12).ToLowerInvariant()
  $iconPath = Join-Path $shortcutIconDir "sanglive-$hash.ico"

  New-Item -ItemType Directory -Force -Path $shortcutIconDir | Out-Null
  Copy-Item -LiteralPath $sourceIconPath -Destination $iconPath -Force

  Get-ChildItem -LiteralPath $shortcutIconDir -Filter 'sanglive-*.ico' -File -ErrorAction SilentlyContinue |
    Where-Object { $_.FullName -ne $iconPath } |
    Remove-Item -Force -ErrorAction SilentlyContinue

  return $iconPath
}

function Create-Shortcut {
  param([string]$ShortcutPath)

  $shortcutDir = Split-Path -Parent $ShortcutPath
  if (-not (Test-Path $shortcutDir)) { New-Item -ItemType Directory -Force -Path $shortcutDir | Out-Null }

  $shell = New-Object -ComObject WScript.Shell
  $shortcut = $shell.CreateShortcut($ShortcutPath)
  $shortcut.TargetPath = 'wscript.exe'
  $shortcut.Arguments = "`"$launcherPath`""
  $shortcut.WorkingDirectory = $root
  if ($shortcutIconPath -and (Test-Path $shortcutIconPath)) {
    $shortcut.IconLocation = "$shortcutIconPath,0"
  }
  $shortcut.Description = 'Start S-Live with tray icon'
  $shortcut.Save()
}

Set-Location $root
Assert-Node

if (-not $NoInstall) {
  npm install --omit=dev --no-audit --no-fund --prefer-offline
  if ($LASTEXITCODE -ne 0) { throw 'npm install failed.' }
}

if (-not $NoShortcut) {
  $shortcutIconPath = Initialize-ShortcutIcon

  $shortcutPath = Join-Path $desktopPath $shortcutName
  try {
    Create-Shortcut -ShortcutPath $shortcutPath
    $oldShortcutPath = Join-Path $desktopPath 'SangLive.lnk'
    if ($oldShortcutPath -ne $shortcutPath -and (Test-Path $oldShortcutPath)) {
      Remove-Item -LiteralPath $oldShortcutPath -Force -ErrorAction SilentlyContinue
    }
    Write-Host "Created shortcut: $shortcutPath"
  } catch {
    Write-Warning "Could not create shortcut at ${shortcutPath}: $($_.Exception.Message)"
  }
}

Write-Host 'Install complete. Use the S-Live Desktop shortcut to start the app.'
