[CmdletBinding()]
param()

$ErrorActionPreference = 'Stop'
$packageRoot = Split-Path -Parent $PSScriptRoot
$sourceRoot = Join-Path $packageRoot 'engine'
$stateRoot = Join-Path $env:LOCALAPPDATA 'CodexDreamSkin'
$installRoot = Join-Path $stateRoot 'engine'
$temporaryRoot = Join-Path $stateRoot "engine.installing.$PID"
$previousRoot = Join-Path $stateRoot "engine.previous.$PID"
$installedNewEngine = $false
$movedPreviousEngine = $false

function Assert-PackageFile {
  param([string]$RelativePath)
  $path = Join-Path $sourceRoot $RelativePath
  if (-not (Test-Path -LiteralPath $path -PathType Leaf)) {
    throw "The download is incomplete. Missing file: $RelativePath"
  }
}

function Assert-NodeRuntime {
  $node = Get-Command node.exe -ErrorAction SilentlyContinue
  if ($null -eq $node) {
    throw 'Node.js 22 or newer is required. Install it from nodejs.org, then double-click the installer again. / 需要先安装 Node.js 22 或更新版本。'
  }
  $version = (& $node.Source --version 2>$null)
  if ($LASTEXITCODE -ne 0 -or "$version" -notmatch '^v(?<major>\d+)\.') {
    throw 'Node.js was found but its version could not be validated.'
  }
  if ([int]$Matches.major -lt 22) {
    throw "Node.js 22 or newer is required; found $version. / 当前版本为 $version，需要升级到 Node.js 22 或更新版本。"
  }
}

try {
  Assert-PackageFile 'scripts\install-dream-skin.ps1'
  Assert-PackageFile 'scripts\start-dream-skin.ps1'
  Assert-PackageFile 'scripts\restore-dream-skin.ps1'
  Assert-PackageFile 'scripts\common-windows.ps1'
  Assert-PackageFile 'assets\dream-skin.css'
  Assert-PackageFile 'assets\renderer-inject.js'
  Assert-NodeRuntime

  New-Item -ItemType Directory -Force -Path $stateRoot | Out-Null
  if (Test-Path -LiteralPath $temporaryRoot) {
    Remove-Item -LiteralPath $temporaryRoot -Recurse -Force
  }
  New-Item -ItemType Directory -Force -Path $temporaryRoot | Out-Null
  Copy-Item -Path (Join-Path $sourceRoot '*') -Destination $temporaryRoot -Recurse -Force

  if (Test-Path -LiteralPath $installRoot) {
    Move-Item -LiteralPath $installRoot -Destination $previousRoot
    $movedPreviousEngine = $true
  }
  Move-Item -LiteralPath $temporaryRoot -Destination $installRoot
  $installedNewEngine = $true

  $installer = Join-Path $installRoot 'scripts\install-dream-skin.ps1'
  & powershell.exe -NoLogo -NoProfile -ExecutionPolicy Bypass -File $installer
  if ($LASTEXITCODE -ne 0) {
    throw "The Dream Skin engine installer exited with code $LASTEXITCODE."
  }

  if ($movedPreviousEngine -and (Test-Path -LiteralPath $previousRoot)) {
    Remove-Item -LiteralPath $previousRoot -Recurse -Force
  }
  Write-Host ''
  Write-Host 'Codex Dream Skin is installed in a stable local folder.' -ForegroundColor Green
  Write-Host 'Codex Dream Skin 已安装到稳定的本机目录。' -ForegroundColor Green
} catch {
  if ($installedNewEngine -and (Test-Path -LiteralPath $installRoot)) {
    Remove-Item -LiteralPath $installRoot -Recurse -Force -ErrorAction SilentlyContinue
  }
  if ($movedPreviousEngine -and (Test-Path -LiteralPath $previousRoot)) {
    Move-Item -LiteralPath $previousRoot -Destination $installRoot -ErrorAction SilentlyContinue
  }
  if (Test-Path -LiteralPath $temporaryRoot) {
    Remove-Item -LiteralPath $temporaryRoot -Recurse -Force -ErrorAction SilentlyContinue
  }
  Write-Host ''
  Write-Host $_.Exception.Message -ForegroundColor Red
  Write-Host 'Nothing under WindowsApps or app.asar was changed.' -ForegroundColor Yellow
  Write-Host 'WindowsApps 和 app.asar 均未被修改。' -ForegroundColor Yellow
  exit 1
}
