<#
.SYNOPSIS
    Formats a script file using PSScriptAnalyzer
.DESCRIPTION
    Formats a script file using PSScriptAnalyzer and some hard-coded rules.
    There are many formatters, but this one is mine.
.EXAMPLE
    Get-ChildItem -Recurse -Filter *.ps1 | Format-ScriptFile
#>
[CmdletBinding()]
param(
    # The path to the script to format
    [Parameter(Mandatory, ValueFromPipeline)]
    [Alias("PSPath")]
    $Path
)
process {
    # $Tokens = $null
    # $ParseErrors = $null
    # $Ast = [System.Management.Automation.Language.Parser]::ParseFile($Path, [ref]$Tokens, [ref]$ParseErrors)

    $FormattedText = PSScriptAnalyzer\Invoke-Formatter -ScriptDefinition (Get-Content $Path -Raw) -Settings @{
        IncludeRules = @(
            "PSPlaceCloseBrace"
            "PSPlaceOpenBrace"
            "PSUseConsistentWhitespace"
            "PSUseConsistentIndentation"
            "PSAlignAssignmentStatement"
            "PSAvoidSemicolonsAsLineTerminators"
            "PSAvoidUsingCmdletAliases"
            "PSUseCorrectCasing"
        )
        Rules = @{
            PSPlaceOpenBrace = @{
                Enable = $true
                OnSameLine = $true
                NewLineAfter = $true
                IgnoreOneLineBlock = $false
            }
            PSPlaceCloseBrace = @{
                Enable = $true
                NewLineAfter = $false
                IgnoreOneLineBlock = $false
            }
            PSUseConsistentIndentation = @{
                Enable = $true
                IndentationSize = 4
                Kind = "spaces"
                PipelineIndentation = "IncreaseIndentationForFirstPipeline"
            }
            PSUseConsistentWhitespace = @{
                Enable = $true
                CheckOpenBrace = $true
                CheckOpenParen = $true
                CheckOperator = $true
                CheckSeparator = $true
                CheckInnerBrace = $true
                CheckParameter = $true
                CheckPipe = $true
                CheckPipeForRedundantWhitespace = $true
            }
            PSAlignAssignmentStatement = @{
                Enable = $false # This conflicts with PSUseConsistentWhitespace CheckOperator
                CheckHashtable = $true
            }
            PSAvoidSemicolonsAsLineTerminators = @{
                Enable = $true
            }
            PSAvoidUsingCmdletAliases = @{
                Enable = $true
            }
            PSUseCorrectCasing = @{
                Enable = $true
            }
        }
    }

    # $FormattedAst = [System.Management.Automation.Language.Parser]::ParseInput($FormattedText, $Path, [ref]$Tokens, [ref]$ParseErrors)
    Set-Content -Path $Path -Value $FormattedText.TrimEnd() -Encoding UTF8
}