[CmdletBinding()]
param()

Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'

$repositoryRoot = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '..\..'))
$wrapper = Join-Path $repositoryRoot 'scripts\Invoke-LegacyPackageLocalStateSmoke.ps1'
$shared = Join-Path $repositoryRoot 'scripts\Invoke-LegacyPackageInputSmoke.ps1'
$harness = Join-Path $repositoryRoot 'scripts\Test-LegacyPackageLocalStateSmoke.mjs'

foreach ($path in @($wrapper, $shared, $harness)) {
    if (-not [IO.File]::Exists($path)) { throw "Missing tracked smoke file: $path" }
}

foreach ($path in @($wrapper, $shared)) {
    $tokens = $null
    $errors = $null
    [void][Management.Automation.Language.Parser]::ParseFile(
        $path,
        [ref]$tokens,
        [ref]$errors)
    if (@($errors).Count -ne 0) {
        throw "PowerShell parser rejected $path."
    }
}

$auditJson = & powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass `
    -File $wrapper -StaticAudit
if ($LASTEXITCODE -ne 0) { throw 'The static audit action failed.' }
$audit = $auditJson | ConvertFrom-Json
if ([string]$audit.result -cne 'PASS' -or
    [string]$audit.profile -cne 'local-settings-comparison-import' -or
    [string]$audit.packageFlavor -cne 'DebugAppX' -or
    [int]$audit.exchangeCount -ne 13 -or
    [int]$audit.physicalClickCount -ne 9 -or
    [int]$audit.folderPickerCancelCount -ne 3 -or
    [int]$audit.fileObservationCount -ne 4 -or
    [int]$audit.inputRetryCount -ne 0 -or
    [string]$audit.expectedSourceSha256 -cne
        '1EE76BC464FB1C44C8B6546E99CDC21C726C0E2C24AD344F5C19AE41BFC0D2F2' -or
    [int]$audit.expectedSourceRows -ne 8 -or
    [string]$audit.expectedFreshDestinationSha256 -cne
        '13C07BA64587549EDA9C1A694F3DFA19875CB1F888F02C9E071F17C47739E087' -or
    [int]$audit.expectedFreshDestinationRows -ne 1 -or
    [string]$audit.expectedImportedDestinationSha256 -cne
        '2575C2420800670B0022EBEE819BA3D9640DB14E9552426DF46075D079F1F697' -or
    [int]$audit.expectedImportedDestinationRows -ne 9 -or
    $audit.sendInputClickAvailable -ne $true -or
    $audit.sendInputEscapeAvailable -ne $true) {
    throw 'The static audit does not expose the closed input/file contract.'
}

$wrapperText = [IO.File]::ReadAllText($wrapper)
$sharedText = [IO.File]::ReadAllText($shared)
$harnessText = [IO.File]::ReadAllText($harness)
foreach ($token in @(
    '-BuildFlavor DebugAppX',
    '-DefinitionsOnly',
    '[string]$LegacyDataDirectory',
    "'..\MBN_STOCK_N\MBN_STOCK_N\bin\Debug\Data'",
    'Assert-LocalFilePreflight',
    'Wait-UniqueOwnedFolderPicker',
    'SendEscapeToForegroundWindow',
    '$ExpectedExchangePlan.Count',
    'The app was intentionally left open; no input retry, guessed cleanup,'
    'comparisonSecondImportAddedCount = 0')) {
    if (-not $wrapperText.Contains($token)) { throw "Missing wrapper contract token: $token" }
}
if ($wrapperText -match '(?i)C:\\Users\\[^\\]+') {
    throw 'The local-state wrapper must not commit a workstation-specific user path.'
}
foreach ($token in @(
    '[switch]$DefinitionsOnly',
    'public static void SendApplicationClick(',
    'bool allowForegroundTransitionAfterClick',
    'public static void SendEscapeToForegroundWindow(',
    'if ($DefinitionsOnly)')) {
    if (-not $sharedText.Contains($token)) { throw "Missing shared guard token: $token" }
}
foreach ($token in @(
    '"choose-operator-folder"',
    '"folder-picker-click-cancel"',
    '"observe-local-files"',
    'receipt?.addedPairCount === expectedFirstAdded',
    'receipt?.skippedDuplicateCount === expectedFirstSkipped',
    'receipt?.addedPairCount === 0',
    'process.stdin.unref',
    'allowMissingState: true',
    'Only the input-free initial preflight',
    'nextInputSequence !== 14',
    'no input was retried')) {
    if (-not $harnessText.Contains($token)) { throw "Missing harness contract token: $token" }
}
if ($wrapperText -match '(?im)^\s*(?:Remove-Item|Stop-Process|taskkill)\b' -or
    $wrapperText.Contains('MBN_STOCK_N') -and
        $wrapperText -match '(?is)(?:WriteAll|OpenWrite|FileMode\]::Create).*MBN_STOCK_N') {
    throw 'The wrapper contains an unsafe cleanup or original-repository write path.'
}

[pscustomobject]@{
    result = 'PASS'
    exchanges = 13
    physicalClicks = 9
    pickerCancels = 3
    observations = 4
    freshImportAdded = 8
    alreadyImportedAdded = 0
    idempotentAdded = 0
} | ConvertTo-Json -Compress
