param(
    [Parameter(Mandatory = $true)]
    [string]$ScriptPath
)

$ErrorActionPreference = 'Stop'

if (-not (Test-Path -LiteralPath $ScriptPath)) {
    Write-Host "[FAIL] PowerShell file not found: $ScriptPath" -ForegroundColor Red
    exit 2
}

$Tokens = $null
$ParseErrors = $null

[System.Management.Automation.Language.Parser]::ParseFile(
    $ScriptPath,
    [ref]$Tokens,
    [ref]$ParseErrors
) | Out-Null

if ($ParseErrors.Count -gt 0) {
    Write-Host '[FAIL] PowerShell parser validation failed.' -ForegroundColor Red

    foreach ($ParseError in $ParseErrors) {
        $Line = $ParseError.Extent.StartLineNumber
        $Column = $ParseError.Extent.StartColumnNumber
        Write-Host (
            "  Line $Line, column $Column: " +
            $ParseError.Message
        ) -ForegroundColor Red
    }

    exit 1
}

Write-Host '[PASS] PowerShell parser validation.'
exit 0
