$ErrorActionPreference = 'Stop'

$sourceRoot = Split-Path -Parent $MyInvocation.MyCommand.Path
$installRoot = Join-Path $env:LOCALAPPDATA 'Zulang\ZhulangApp'
$exeSource = Get-ChildItem -LiteralPath $sourceRoot -Filter 'Zhulang-*-portable.exe' -File |
  Sort-Object LastWriteTime -Descending |
  Select-Object -First 1
$iconSource = Join-Path $sourceRoot 'icon.ico'

if (-not $exeSource) {
  throw 'Missing installer file: Zhulang-*-portable.exe'
}
$exeName = $exeSource.Name

New-Item -ItemType Directory -Force -Path $installRoot | Out-Null
Copy-Item -LiteralPath $exeSource.FullName -Destination (Join-Path $installRoot $exeName) -Force
if (Test-Path $iconSource) {
  Copy-Item -LiteralPath $iconSource -Destination (Join-Path $installRoot 'icon.ico') -Force
}

$desktop = [Environment]::GetFolderPath('Desktop')
$programs = [Environment]::GetFolderPath('Programs')
$startMenu = Join-Path $programs 'Zhulang'
New-Item -ItemType Directory -Force -Path $startMenu | Out-Null

function New-ZulangShortcut($path) {
  $shell = New-Object -ComObject WScript.Shell
  $shortcut = $shell.CreateShortcut($path)
  $shortcut.TargetPath = Join-Path $installRoot $exeName
  $shortcut.WorkingDirectory = $installRoot
  $shortcut.Description = 'Zhulang Local AI Platform'
  $iconPath = Join-Path $installRoot 'icon.ico'
  if (Test-Path $iconPath) {
    $shortcut.IconLocation = $iconPath
  }
  $shortcut.Save()
}

$desktopShortcut = Join-Path $desktop 'Zhulang Local AI Platform.lnk'
$startMenuShortcut = Join-Path $startMenu 'Zhulang Local AI Platform.lnk'

New-ZulangShortcut $desktopShortcut
New-ZulangShortcut $startMenuShortcut

Write-Host 'Zhulang Local AI Platform installed.'
Write-Host ('Install path: ' + $installRoot)
Write-Host ('Desktop shortcut: ' + $desktopShortcut)
