# ASCII only
# selfapps_justme.ps1 - Verify that the JustMe Miniconda install path executed.
# Lane: justme-test only. Asserts that ~setup.log contains the JustMe install message.
param()
$ErrorActionPreference = 'Continue'
$here = $PSScriptRoot
$repo = Split-Path -Path $here -Parent
$nd   = Join-Path $here '~test-results.ndjson'
$ciNd = Join-Path $repo 'ci_test_results.ndjson'
if (-not (Test-Path $nd))   { New-Item -ItemType File -Path $nd   -Force | Out-Null }
if (-not (Test-Path $ciNd)) { New-Item -ItemType File -Path $ciNd -Force | Out-Null }

function Write-NdjsonRow {
    param([hashtable]$Row)
    $lane = [Environment]::GetEnvironmentVariable('HP_CI_LANE')
    if ($lane -and -not $Row.ContainsKey('lane')) { $Row['lane'] = $lane }
    $json = $Row | ConvertTo-Json -Compress -Depth 8
    Add-Content -LiteralPath $nd   -Value $json -Encoding Ascii
    Add-Content -LiteralPath $ciNd -Value $json -Encoding Ascii
}

# Non-Windows skip
if ([System.Environment]::OSVersion.Platform -ne [System.PlatformID]::Win32NT) {
    $platform = [System.Environment]::OSVersion.Platform.ToString()
    Write-NdjsonRow ([ordered]@{
        id      = 'conda.install.justme'
        req     = 'REQ-003'
        pass    = $true
        desc    = 'Miniconda JustMe install path executed successfully'
        details = [ordered]@{ skip = $true; platform = $platform; reason = 'non-windows-host' }
    })
    exit 0
}

# Read the envsmoke ~setup.log which is written by the bootstrap that ran with HP_TEST_NOT_ELEVATED=1.
# The justme-test lane runs selfapps_envsmoke.ps1 first (which executes run_setup.bat),
# so the setup log is at tests/~envsmoke/~setup.log.
$setupLogPath = Join-Path $here '~envsmoke\~setup.log'
$setupText = ''
if (Test-Path -LiteralPath $setupLogPath) {
    $setupText = Get-Content -LiteralPath $setupLogPath -Raw -Encoding Ascii
}

# Also check the main bootstrap log written at repo root
$mainSetupPath = Join-Path $repo '~setup.log'
$mainSetupText = ''
if (Test-Path -LiteralPath $mainSetupPath) {
    $mainSetupText = Get-Content -LiteralPath $mainSetupPath -Raw -Encoding Ascii
}

$combinedText = $setupText + $mainSetupText

# derived requirement: the JustMe path log line must appear to confirm the fallback ran.
# HP_TEST_NOT_ELEVATED=1 simulates a non-admin process: run_setup.bat logs
# "[INFO] Not elevated; skipping AllUsers Miniconda install." and then runs the JustMe install,
# which logs "[INFO] Miniconda installed (JustMe fallback)."
$notElevatedSkip = $combinedText -match 'Not elevated; skipping AllUsers Miniconda install\.'
$justmeInstalled = $combinedText -match 'Miniconda installed \(JustMe fallback\)'

# derived requirement: [Active Backlog item 16, renumbered from 11 -- see docs/agent-closed-
# backlog.md] the shared :tci_justme label must NOT claim AllUsers "failed" when it was only ever
# skipped (never launched) -- this scenario's own HP_TEST_NOT_ELEVATED=1 takes the skip path, so
# the correct line is the INFO "skipped" wording, and no "AllUsers install failed" WARN wording
# (any variant -- exitCode/reason or timeout) must appear at all in this run. Checked against
# $setupText (the envsmoke-scoped log for THIS specific sub-bootstrap) rather than $combinedText
# -- unlike the two pre-existing presence checks above, a negative ("must NOT appear") assertion
# would be vulnerable to stale/unrelated content in the shared repo-root ~setup.log if it were
# ever written by an earlier, different step in the same job.
#
# Matches on the stable "Miniconda AllUsers install failed" PREFIX, not a full literal sentence --
# a prior version of this assertion matched the exact pre-exitCode-annotation wording, which no
# longer appears anywhere (the WARN line always carries exitCode=.../reason=... or reason=timeout
# now), so that check had silently degraded into an assertion that could never fail regardless of
# whether the skip-path regression it exists to catch actually recurred.
$skippedWordingCorrect = $setupText -match 'Miniconda AllUsers install skipped \(not elevated\); trying JustMe install instead\.'
$failedWordingAbsent   = -not ($setupText -match 'Miniconda AllUsers install failed')

$pass = $notElevatedSkip -and $justmeInstalled -and $skippedWordingCorrect -and $failedWordingAbsent

Write-NdjsonRow ([ordered]@{
    id      = 'conda.install.justme'
    req     = 'REQ-003'
    pass    = $pass
    desc    = 'Miniconda JustMe install path executed (non-elevated simulation)'
    details = [ordered]@{
        notElevatedSkip        = $notElevatedSkip
        justmeInstalled        = $justmeInstalled
        skippedWordingCorrect  = $skippedWordingCorrect
        failedWordingAbsent    = $failedWordingAbsent
        setupLog               = $setupLogPath
    }
})

if (-not $pass) { exit 1 }
exit 0
