#Requires -Version 5.1

# Standalone dashboard launcher.
# Uses the Node.js runtime bundled in .\node when present, falling back to a
# system-wide Node.js install for packages that don't include a runtime.

$ErrorActionPreference = "Stop"

$RequiredVersion = [version]"22.12.0"
$DownloadUrl = "https://whitestar.io/downloads/dashboard"

$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
Set-Location $ScriptDir

# Prefer the bundled Node.js runtime; otherwise require a recent system Node.js
$BundledNode = Join-Path $ScriptDir "node\node.exe"
if (Test-Path $BundledNode) {
    # Put the bundled runtime first on PATH so npm lifecycle scripts that
    # spawn "node" also use it
    $env:Path = (Join-Path $ScriptDir "node") + ";" + $env:Path
    $NodeBin = $BundledNode
    $NpmBin = Join-Path $ScriptDir "node\npm.cmd"
}
elseif (Get-Command node -ErrorAction SilentlyContinue) {
    $NodeBin = "node"
    $NpmBin = "npm"
    $NodeVersion = [version]((node -v) -replace '^v', '')
    if ($NodeVersion -lt $RequiredVersion) {
        Write-Host "❌ Node.js version $NodeVersion is not supported. Please update to v$RequiredVersion or later, or download the package for your platform (which includes Node.js) from $DownloadUrl" -ForegroundColor Red
        exit 1
    }
}
else {
    Write-Host "❌ Node.js is not installed. Download the package for your platform (which includes Node.js) from $DownloadUrl" -ForegroundColor Red
    exit 1
}

# If node_modules folder does not exist, run npm install
if (-not (Test-Path "node_modules")) {
    Write-Host "📦 node_modules folder does not exist. Running npm install..." -ForegroundColor Cyan
    & $NpmBin install
    if ($LASTEXITCODE -ne 0) {
        Write-Host "❌ npm install failed. See the output above for details." -ForegroundColor Red
        exit 1
    }
    Write-Host "✅ npm install completed" -ForegroundColor Green
}

# First run: create the local database from the bundled default
if (-not (Test-Path "packages\standalone\dashboard.db") -and (Test-Path "packages\standalone\default-database.db")) {
    Write-Host "🗄️  Creating dashboard.db from the default database..." -ForegroundColor Cyan
    Copy-Item "packages\standalone\default-database.db" "packages\standalone\dashboard.db"
}

# Check for updates
Write-Host "🔄 Checking for updates..." -ForegroundColor Cyan
try {
    $RemoteVersion = (Invoke-WebRequest -Uri "$DownloadUrl/release.txt" -UseBasicParsing).Content.Trim()
}
catch {
    $RemoteVersion = $null
}
$LocalVersion = if (Test-Path ".\release.txt") { (Get-Content ".\release.txt" -Raw).Trim() } else { "0" }

if ($RemoteVersion -notmatch '^\d+$') {
    Write-Host "⚠️  Could not check for updates (network error)" -ForegroundColor Yellow
}
elseif ([int]$RemoteVersion -gt [int]$LocalVersion) {
    Write-Host "📬 An update is available! (v$RemoteVersion > v$LocalVersion)" -ForegroundColor Green
    $Reply = Read-Host "Would you like to download and install the update now? (y/n)"
    if ($Reply -match '^[Yy]$') {
        Write-Host "📥 Downloading update..." -ForegroundColor Cyan
        $TempZip = Join-Path $env:TEMP "dashboard-update.zip"
        try {
            Invoke-WebRequest -Uri "$DownloadUrl/dashboard-win-x64.zip" -OutFile $TempZip

            Write-Host "📦 Extracting update..." -ForegroundColor Cyan
            Expand-Archive -Path $TempZip -DestinationPath $ScriptDir -Force
            Remove-Item $TempZip -ErrorAction SilentlyContinue
            Write-Host "✅ Update installed successfully! Restarting..." -ForegroundColor Green

            & powershell.exe -NoProfile -ExecutionPolicy Bypass -File (Join-Path $ScriptDir "start.ps1")
            exit $LASTEXITCODE
        }
        catch {
            Write-Host "❌ Failed to download update" -ForegroundColor Red
        }
    }
}
else {
    Write-Host "✅ You are running the latest version (v$LocalVersion)" -ForegroundColor Green
}

Write-Host "🚀 Starting server..." -ForegroundColor Cyan

$env:HOSTNAME = "0.0.0.0"
& $NodeBin .\packages\standalone\server.js
