# Priority Forge — experimental Windows-native installer.
#
# STATUS: scaffolding only. Prefer the WSL install path documented in the
# top-level README. This script registers the backend + frontend as Task
# Scheduler logon-triggered tasks. It does NOT:
#   - install dependencies (run `npm install` first, with Node 20+ on PATH)
#   - seed the database (run `npm run seed`)
#   - configure MCP (run `npm run setup:mcp`)
#   - install a watchdog
#
# See windows/README.md for the full caveat list.

[CmdletBinding()]
param(
    [switch]$WhatIf,
    [string]$NodeExe = (Get-Command node.exe -ErrorAction SilentlyContinue).Path
)

$ErrorActionPreference = 'Stop'

$repoRoot = Split-Path -Parent $PSScriptRoot
$tasksDir = Join-Path $env:LOCALAPPDATA 'priority-forge\tasks'
$null = New-Item -ItemType Directory -Force -Path $tasksDir

if (-not $NodeExe -or -not (Test-Path $NodeExe)) {
    throw "Could not locate node.exe. Install Node 20+ or pass -NodeExe 'C:\path\to\node.exe'."
}

$userId = (whoami)

$tokens = @{
    '@@NODE_EXE@@'    = $NodeExe
    '@@INSTALL_DIR@@' = $repoRoot
    '@@USERPROFILE@@' = $env:USERPROFILE
    '@@USER_ID@@'     = $userId
}

$templates = @(
    @{ Name = 'backend';  Source = 'priority-forge-backend.task.xml.template' }
    @{ Name = 'frontend'; Source = 'priority-forge-frontend.task.xml.template' }
)

foreach ($tpl in $templates) {
    $src = Join-Path $PSScriptRoot $tpl.Source
    $dst = Join-Path $tasksDir ("priority-forge-{0}.task.xml" -f $tpl.Name)
    $content = Get-Content -Raw -Path $src
    foreach ($k in $tokens.Keys) {
        $content = $content -replace [regex]::Escape($k), $tokens[$k]
    }
    Set-Content -Path $dst -Value $content -Encoding Unicode

    $taskName = "PriorityForge\$($tpl.Name)"
    if ($WhatIf) {
        Write-Host "[WhatIf] would register: $taskName  <- $dst"
    }
    else {
        # /f overwrites if the task already exists; safe because we use a
        # stable, namespaced URI.
        schtasks.exe /create /xml "$dst" /tn $taskName /f | Out-Host
        Write-Host "registered: $taskName"
    }
}

Write-Host ""
Write-Host "Done. Tasks will start at next logon, or trigger now with:"
Write-Host "    schtasks.exe /run /tn PriorityForge\backend"
Write-Host "    schtasks.exe /run /tn PriorityForge\frontend"
Write-Host ""
Write-Host "Uninstall:"
Write-Host "    schtasks.exe /delete /tn PriorityForge\backend /f"
Write-Host "    schtasks.exe /delete /tn PriorityForge\frontend /f"
