#Requires -Version 5.1
<#
.SYNOPSIS
  Install or build Vigthoria Workbench on Windows.

.DESCRIPTION
  Builds the Tauri app, runs the MSI installer when available, and reports paths.

  Usage:
    .\install.ps1              # build + install MSI (passive)
    .\install.ps1 -Dev         # run in dev mode (tauri dev)
    .\install.ps1 -SkipMsi     # build only, do not run MSI
#>
param(
  [switch]$Dev,
  [switch]$SkipMsi
)

$ErrorActionPreference = "Stop"
$Root = Split-Path -Parent $MyInvocation.MyCommand.Path

function Test-Command($name) {
  return [bool](Get-Command $name -ErrorAction SilentlyContinue)
}

function Refresh-ShellPath {
  $machine = [Environment]::GetEnvironmentVariable("Path", "Machine")
  $user = [Environment]::GetEnvironmentVariable("Path", "User")
  if ($machine -and $user) { $env:Path = "$machine;$user" }
  $cargoBin = Join-Path $env:USERPROFILE ".cargo\bin"
  if ((Test-Path $cargoBin) -and ($env:Path -notlike "*$cargoBin*")) {
    $env:Path = "$cargoBin;$env:Path"
  }
}

function Test-CargoInstalled {
  Refresh-ShellPath
  if (Test-Command cargo) { return $true }
  return Test-Path (Join-Path $env:USERPROFILE ".cargo\bin\cargo.exe")
}

Write-Host ""
Write-Host "=============================================================" -ForegroundColor Cyan
Write-Host "           VIGTHORIA WORKBENCH - Windows Setup" -ForegroundColor Cyan
Write-Host "=============================================================" -ForegroundColor Cyan
Write-Host ""

if (-not (Test-Command node)) {
  Write-Host "Node.js is required. Install: winget install OpenJS.NodeJS.LTS" -ForegroundColor Red
  exit 1
}
if (-not (Test-CargoInstalled)) {
  Write-Host "Rust is required. Install: winget install Rustlang.Rustup" -ForegroundColor Red
  Write-Host "Then close this window, open a NEW PowerShell, and run the installer again." -ForegroundColor Yellow
  exit 1
}
Refresh-ShellPath

Write-Host "Node:  $(node -v)" -ForegroundColor Gray
Write-Host "Rust:  $(rustc --version)" -ForegroundColor Gray
Write-Host ""

Push-Location $Root
try {
  Write-Host "Installing npm dependencies..." -ForegroundColor Cyan
  npm install --no-audit --no-fund

  if ($Dev) {
    Write-Host "Starting Workbench in dev mode..." -ForegroundColor Green
    npm run tauri:dev
    exit $LASTEXITCODE
  }

  Write-Host "Building Vigthoria Workbench (first build may take 10-20 minutes)..." -ForegroundColor Cyan
  npm run tauri:build
  if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }

  $msi = Get-ChildItem -Path "$Root\src-tauri\target\release\bundle\nsis\*.msi" -ErrorAction SilentlyContinue | Select-Object -First 1
  $installedExe = Join-Path $env:LOCALAPPDATA "Programs\Vigthoria Workbench\Vigthoria Workbench.exe"

  if ($msi -and -not $SkipMsi) {
    Write-Host ""
    Write-Host "Running Windows installer: $($msi.Name)" -ForegroundColor Cyan
    $proc = Start-Process -FilePath "msiexec.exe" -ArgumentList @("/i", "`"$($msi.FullName)`"", "/passive") -Wait -PassThru
    if ($proc.ExitCode -ne 0) {
      Write-Host "msiexec exit code: $($proc.ExitCode). You can double-click the MSI manually:" -ForegroundColor Yellow
      Write-Host "  $($msi.FullName)" -ForegroundColor White
    } else {
      Write-Host "MSI installation finished." -ForegroundColor Green
    }
  } elseif ($msi) {
    Write-Host ""
    Write-Host "MSI built (SkipMsi): $($msi.FullName)" -ForegroundColor Green
  }

  if (Test-Path $installedExe) {
    Write-Host ""
    Write-Host "Installed app: $installedExe" -ForegroundColor Green
  } else {
    $exe = Get-ChildItem -Path "$Root\src-tauri\target\release" -Filter "*.exe" -Recurse -ErrorAction SilentlyContinue |
      Where-Object { $_.Name -match "Vigthoria Workbench" } | Select-Object -First 1
    if ($exe) {
      Write-Host "Built executable: $($exe.FullName)" -ForegroundColor Green
    } else {
      Write-Host "Check bundle output: src-tauri\target\release\bundle\" -ForegroundColor Yellow
    }
  }

  Write-Host ""
  Write-Host "Ensuring Vigthoria CLI 1.13.13 is installed..." -ForegroundColor Cyan
  npm install -g "https://extension.vigthoria.io/downloads/vigthoria-cli-1.13.13.tgz"
  if ($LASTEXITCODE -ne 0) {
    Write-Host "CLI installation failed. Retry with:" -ForegroundColor Yellow
    Write-Host "  npm install -g https://extension.vigthoria.io/downloads/vigthoria-cli-1.13.13.tgz" -ForegroundColor White
  }
  Write-Host ""
  Write-Host "After install, use Install-Vigthoria-Workbench.ps1 or create shortcuts to launch." -ForegroundColor Gray
}
finally {
  Pop-Location
}
