Private/New-PstScriptContent.ps1

function New-PstScriptContent {
    <#
    .SYNOPSIS
        Generates PowerShell script content based on complexity level.

    .DESCRIPTION
        Creates complete script content with appropriate structure and features
        based on the specified complexity level. Scripts differ from functions
        in that they have a #Requires header, script-level parameters, and
        main execution logic without a function wrapper.

        Basic: Simple script with basic parameters and try/catch
        Standard: Production script with CmdletBinding, validation, and logging
        Advanced: Full script with configuration, transcript, and cleanup

    .PARAMETER ScriptName
        The name of the script being generated (used in documentation).

    .PARAMETER Complexity
        The complexity level. Valid values: Basic, Standard, Advanced.

    .PARAMETER Parameters
        Array of normalized parameter definitions.

    .PARAMETER Synopsis
        Brief description for the script header.

    .PARAMETER Description
        Detailed description for the script header.

    .PARAMETER Examples
        Array of usage examples.

    .PARAMETER Notes
        Additional notes for the header.

    .PARAMETER Author
        Author name for the header.

    .EXAMPLE
        New-PstScriptContent -ScriptName "Deploy-Application" -Complexity "Standard"
        Generates a Standard complexity script template.

    .NOTES
        Version: 1.0
        Author: numidia
        Creation Date: 2025-12-03
        Purpose/Change: Script generation for intelligent code generation system
    #>

    [CmdletBinding()]
    [OutputType([string])]
    param (
        [Parameter(Mandatory = $true, Position = 0)]
        [ValidateNotNullOrEmpty()]
        [string]$ScriptName,

        [Parameter(Mandatory = $false, Position = 1)]
        [ValidateSet("Basic", "Standard", "Advanced")]
        [string]$Complexity = "Standard",

        [Parameter(Mandatory = $false)]
        [object[]]$Parameters = @(),

        [Parameter(Mandatory = $false)]
        [string]$Synopsis,

        [Parameter(Mandatory = $false)]
        [string]$Description,

        [Parameter(Mandatory = $false)]
        [string[]]$Examples,

        [Parameter(Mandatory = $false)]
        [string]$Notes,

        [Parameter(Mandatory = $false)]
        [string]$Author = 'numidia'
    )

    begin {
        Write-Debug "Begin '$($MyInvocation.MyCommand.Name)' at '$(Get-Date)'"
        $sb = [System.Text.StringBuilder]::new()

        # Set defaults
        if (-not $Synopsis) { $Synopsis = "Brief description of $ScriptName script" }
        if (-not $Description) { $Description = "Detailed description of what $ScriptName does." }
        if (-not $Examples -or $Examples.Count -eq 0) { $Examples = @(".\$ScriptName.ps1 -Parameter Value") }
    }

    process {
        switch ($Complexity) {
            "Basic" {
                # Basic: Simple script structure
                [void]$sb.AppendLine("<#")
                [void]$sb.AppendLine(".SYNOPSIS")
                [void]$sb.AppendLine(" $Synopsis")
                [void]$sb.AppendLine("")
                [void]$sb.AppendLine(".DESCRIPTION")
                [void]$sb.AppendLine(" $Description")
                [void]$sb.AppendLine("")

                # Parameters documentation
                foreach ($param in $Parameters) {
                    $paramName = if ($param -is [hashtable]) { $param.Name } else { $param.ToString() }
                    [void]$sb.AppendLine(".PARAMETER $paramName")
                    [void]$sb.AppendLine(" Description of $paramName parameter.")
                    [void]$sb.AppendLine("")
                }

                # Example
                [void]$sb.AppendLine(".EXAMPLE")
                [void]$sb.AppendLine(" $($Examples[0])")
                [void]$sb.AppendLine(" Example description.")
                [void]$sb.AppendLine("#>")
                [void]$sb.AppendLine("")

                # Parameters block
                if ($Parameters.Count -gt 0) {
                    [void]$sb.AppendLine("param (")
                    for ($i = 0; $i -lt $Parameters.Count; $i++) {
                        $param = $Parameters[$i]
                        $paramName = if ($param -is [hashtable]) { $param.Name } else { $param.ToString() }
                        $paramType = if ($param -is [hashtable] -and $param.ContainsKey('Type')) { $param.Type } else { 'string' }
                        $comma = if ($i -lt $Parameters.Count - 1) { ',' } else { '' }
                        [void]$sb.AppendLine(" [$paramType]`$$paramName$comma")
                    }
                    [void]$sb.AppendLine(")")
                    [void]$sb.AppendLine("")
                }

                # Main logic
                [void]$sb.AppendLine("# Main script logic")
                [void]$sb.AppendLine("try {")
                [void]$sb.AppendLine(" # Your code here")
                [void]$sb.AppendLine(" Write-Output `"Script executed successfully`"")
                [void]$sb.AppendLine("}")
                [void]$sb.AppendLine("catch {")
                [void]$sb.AppendLine(" Write-Error `"An error occurred: `$(`$_.Exception.Message)`"")
                [void]$sb.AppendLine("}")
            }

            "Standard" {
                # Standard: Production-ready script
                [void]$sb.AppendLine("#Requires -Version 5.1")
                [void]$sb.AppendLine("")
                [void]$sb.AppendLine("<#")
                [void]$sb.AppendLine(".SYNOPSIS")
                [void]$sb.AppendLine(" $Synopsis")
                [void]$sb.AppendLine("")
                [void]$sb.AppendLine(".DESCRIPTION")
                [void]$sb.AppendLine(" $Description")
                [void]$sb.AppendLine("")

                # Parameters documentation
                foreach ($param in $Parameters) {
                    $paramName = if ($param -is [hashtable]) { $param.Name } else { $param.ToString() }
                    [void]$sb.AppendLine(".PARAMETER $paramName")
                    [void]$sb.AppendLine(" Description of $paramName parameter.")
                    [void]$sb.AppendLine("")
                }

                # Examples
                foreach ($example in $Examples) {
                    [void]$sb.AppendLine(".EXAMPLE")
                    [void]$sb.AppendLine(" $example")
                    [void]$sb.AppendLine(" Example description.")
                    [void]$sb.AppendLine("")
                }

                [void]$sb.AppendLine(".NOTES")
                [void]$sb.AppendLine(" Version: 1.0")
                [void]$sb.AppendLine(" Author: $Author")
                [void]$sb.AppendLine(" Creation Date: $(Get-Date -Format 'yyyy-MM-dd')")
                if ($Notes) {
                    [void]$sb.AppendLine(" Purpose/Change: $Notes")
                } else {
                    [void]$sb.AppendLine(" Purpose/Change: Initial script development")
                }
                [void]$sb.AppendLine("#>")
                [void]$sb.AppendLine("")
                [void]$sb.AppendLine("[CmdletBinding(SupportsShouldProcess)]")
                [void]$sb.AppendLine("param (")

                # Generate parameters
                if ($Parameters.Count -gt 0) {
                    for ($i = 0; $i -lt $Parameters.Count; $i++) {
                        $param = $Parameters[$i]
                        $paramName = if ($param -is [hashtable]) { $param.Name } else { $param.ToString() }
                        $paramType = if ($param -is [hashtable] -and $param.ContainsKey('Type')) { $param.Type } else { 'string' }
                        $isMandatory = if ($param -is [hashtable] -and $param.ContainsKey('Mandatory')) { $param.Mandatory } else { $false }
                        $comma = if ($i -lt $Parameters.Count - 1) { ',' } else { '' }

                        [void]$sb.AppendLine(" [Parameter(Mandatory = `$$isMandatory)]")
                        [void]$sb.AppendLine(" [ValidateNotNullOrEmpty()]")
                        [void]$sb.AppendLine(" [$paramType]`$$paramName$comma")
                        if ($i -lt $Parameters.Count - 1) { [void]$sb.AppendLine("") }
                    }
                } else {
                    [void]$sb.AppendLine(" # Add parameters here")
                }

                [void]$sb.AppendLine(")")
                [void]$sb.AppendLine("")
                [void]$sb.AppendLine("#region Initialization")
                [void]$sb.AppendLine("")
                [void]$sb.AppendLine('$ErrorActionPreference = "Stop"')
                [void]$sb.AppendLine('Write-Verbose "Starting $($MyInvocation.MyCommand.Name) at $(Get-Date)"')
                [void]$sb.AppendLine("")
                [void]$sb.AppendLine("#endregion Initialization")
                [void]$sb.AppendLine("")
                [void]$sb.AppendLine("#region Main Logic")
                [void]$sb.AppendLine("")
                [void]$sb.AppendLine("try {")
                [void]$sb.AppendLine(' Write-Verbose "Processing..."')
                [void]$sb.AppendLine("")
                [void]$sb.AppendLine(" # Your main logic here")
                [void]$sb.AppendLine(' if ($PSCmdlet.ShouldProcess("Target", "Action")) {')
                [void]$sb.AppendLine(" # Perform the action")
                [void]$sb.AppendLine(" }")
                [void]$sb.AppendLine("")
                [void]$sb.AppendLine(' Write-Verbose "Completed successfully"')
                [void]$sb.AppendLine("}")
                [void]$sb.AppendLine("catch {")
                [void]$sb.AppendLine(' Write-Error "An error occurred: $($_.Exception.Message)"')
                [void]$sb.AppendLine(" throw")
                [void]$sb.AppendLine("}")
                [void]$sb.AppendLine("finally {")
                [void]$sb.AppendLine(' Write-Verbose "Finished $($MyInvocation.MyCommand.Name) at $(Get-Date)"')
                [void]$sb.AppendLine("}")
                [void]$sb.AppendLine("")
                [void]$sb.AppendLine("#endregion Main Logic")
            }

            "Advanced" {
                # Advanced: Full-featured enterprise script
                [void]$sb.AppendLine("#Requires -Version 5.1")
                [void]$sb.AppendLine("#Requires -RunAsAdministrator")
                [void]$sb.AppendLine("")
                [void]$sb.AppendLine("<#")
                [void]$sb.AppendLine(".SYNOPSIS")
                [void]$sb.AppendLine(" $Synopsis")
                [void]$sb.AppendLine("")
                [void]$sb.AppendLine(".DESCRIPTION")
                [void]$sb.AppendLine(" $Description")
                [void]$sb.AppendLine("")
                [void]$sb.AppendLine(" This script includes:")
                [void]$sb.AppendLine(" - Comprehensive error handling")
                [void]$sb.AppendLine(" - Transcript logging")
                [void]$sb.AppendLine(" - Configuration management")
                [void]$sb.AppendLine(" - Progress tracking")
                [void]$sb.AppendLine("")

                # Parameters documentation
                foreach ($param in $Parameters) {
                    $paramName = if ($param -is [hashtable]) { $param.Name } else { $param.ToString() }
                    [void]$sb.AppendLine(".PARAMETER $paramName")
                    [void]$sb.AppendLine(" Description of $paramName parameter.")
                    [void]$sb.AppendLine("")
                }

                # Examples
                foreach ($example in $Examples) {
                    [void]$sb.AppendLine(".EXAMPLE")
                    [void]$sb.AppendLine(" $example")
                    [void]$sb.AppendLine(" Example description.")
                    [void]$sb.AppendLine("")
                }

                [void]$sb.AppendLine(".NOTES")
                [void]$sb.AppendLine(" Version: 1.0")
                [void]$sb.AppendLine(" Author: $Author")
                [void]$sb.AppendLine(" Creation Date: $(Get-Date -Format 'yyyy-MM-dd')")
                if ($Notes) {
                    [void]$sb.AppendLine(" Purpose/Change: $Notes")
                } else {
                    [void]$sb.AppendLine(" Purpose/Change: Initial script development")
                }
                [void]$sb.AppendLine("")
                [void]$sb.AppendLine(".LINK")
                [void]$sb.AppendLine(" https://github.com/your-repo/your-project")
                [void]$sb.AppendLine("#>")
                [void]$sb.AppendLine("")
                [void]$sb.AppendLine("[CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Medium')]")
                [void]$sb.AppendLine("param (")

                # Generate parameters with full attributes
                if ($Parameters.Count -gt 0) {
                    for ($i = 0; $i -lt $Parameters.Count; $i++) {
                        $param = $Parameters[$i]
                        $paramName = if ($param -is [hashtable]) { $param.Name } else { $param.ToString() }
                        $paramType = if ($param -is [hashtable] -and $param.ContainsKey('Type')) { $param.Type } else { 'string' }
                        $isMandatory = if ($param -is [hashtable] -and $param.ContainsKey('Mandatory')) { $param.Mandatory } else { $false }
                        $comma = if ($i -lt $Parameters.Count - 1) { ',' } else { '' }

                        [void]$sb.AppendLine(" [Parameter(Mandatory = `$$isMandatory,")
                        [void]$sb.AppendLine(" HelpMessage = `"Enter $paramName value`")]")
                        [void]$sb.AppendLine(" [ValidateNotNullOrEmpty()]")
                        [void]$sb.AppendLine(" [$paramType]`$$paramName$comma")
                        if ($i -lt $Parameters.Count - 1) { [void]$sb.AppendLine("") }
                    }
                } else {
                    [void]$sb.AppendLine(" [Parameter(Mandatory = `$false,")
                    [void]$sb.AppendLine(" HelpMessage = `"Path to configuration file`")]")
                    [void]$sb.AppendLine(" [ValidateScript({ Test-Path `$_ -PathType Leaf })]")
                    [void]$sb.AppendLine(" [string]`$ConfigPath")
                }

                [void]$sb.AppendLine(")")
                [void]$sb.AppendLine("")
                [void]$sb.AppendLine("#region Configuration")
                [void]$sb.AppendLine("")
                [void]$sb.AppendLine('$ErrorActionPreference = "Stop"')
                [void]$sb.AppendLine('$ProgressPreference = "Continue"')
                [void]$sb.AppendLine("")
                [void]$sb.AppendLine("# Script-level variables")
                [void]$sb.AppendLine('$script:ScriptName = $MyInvocation.MyCommand.Name')
                [void]$sb.AppendLine('$script:ScriptPath = $PSScriptRoot')
                [void]$sb.AppendLine('$script:LogPath = Join-Path $env:TEMP "$script:ScriptName.log"')
                [void]$sb.AppendLine('$script:StartTime = Get-Date')
                [void]$sb.AppendLine("")
                [void]$sb.AppendLine("#endregion Configuration")
                [void]$sb.AppendLine("")
                [void]$sb.AppendLine("#region Helper Functions")
                [void]$sb.AppendLine("")
                [void]$sb.AppendLine("function Write-Log {")
                [void]$sb.AppendLine(" param (")
                [void]$sb.AppendLine(" [Parameter(Mandatory)]")
                [void]$sb.AppendLine(" [string]`$Message,")
                [void]$sb.AppendLine("")
                [void]$sb.AppendLine(" [ValidateSet('Info', 'Warning', 'Error')]")
                [void]$sb.AppendLine(" [string]`$Level = 'Info'")
                [void]$sb.AppendLine(" )")
                [void]$sb.AppendLine("")
                [void]$sb.AppendLine(' $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"')
                [void]$sb.AppendLine(' $logMessage = "[$timestamp] [$Level] $Message"')
                [void]$sb.AppendLine("")
                [void]$sb.AppendLine(" switch (`$Level) {")
                [void]$sb.AppendLine(" 'Info' { Write-Verbose `$logMessage }")
                [void]$sb.AppendLine(" 'Warning' { Write-Warning `$Message }")
                [void]$sb.AppendLine(" 'Error' { Write-Error `$Message }")
                [void]$sb.AppendLine(" }")
                [void]$sb.AppendLine("")
                [void]$sb.AppendLine(' Add-Content -Path $script:LogPath -Value $logMessage')
                [void]$sb.AppendLine("}")
                [void]$sb.AppendLine("")
                [void]$sb.AppendLine("#endregion Helper Functions")
                [void]$sb.AppendLine("")
                [void]$sb.AppendLine("#region Main Logic")
                [void]$sb.AppendLine("")
                [void]$sb.AppendLine("try {")
                [void]$sb.AppendLine(" # Start transcript for debugging")
                [void]$sb.AppendLine(' $transcriptPath = Join-Path $env:TEMP "$script:ScriptName-$(Get-Date -Format ''yyyyMMdd-HHmmss'').transcript"')
                [void]$sb.AppendLine(' Start-Transcript -Path $transcriptPath -Append | Out-Null')
                [void]$sb.AppendLine("")
                [void]$sb.AppendLine(' Write-Log "Script started: $script:ScriptName"')
                [void]$sb.AppendLine(' Write-Log "Parameters: $($PSBoundParameters | ConvertTo-Json -Compress)"')
                [void]$sb.AppendLine("")
                [void]$sb.AppendLine(" # Initialize progress")
                [void]$sb.AppendLine(' $progressParams = @{')
                [void]$sb.AppendLine(" Activity = `$script:ScriptName")
                [void]$sb.AppendLine(" Status = 'Initializing...'")
                [void]$sb.AppendLine(" PercentComplete = 0")
                [void]$sb.AppendLine(" }")
                [void]$sb.AppendLine(' Write-Progress @progressParams')
                [void]$sb.AppendLine("")
                [void]$sb.AppendLine(" #region Processing")
                [void]$sb.AppendLine("")
                [void]$sb.AppendLine(' if ($PSCmdlet.ShouldProcess("Target", "Perform action")) {')
                [void]$sb.AppendLine(" # Your main processing logic here")
                [void]$sb.AppendLine(' Write-Log "Processing..."')
                [void]$sb.AppendLine("")
                [void]$sb.AppendLine(" # Update progress")
                [void]$sb.AppendLine(" `$progressParams.Status = 'Processing...'")
                [void]$sb.AppendLine(" `$progressParams.PercentComplete = 50")
                [void]$sb.AppendLine(' Write-Progress @progressParams')
                [void]$sb.AppendLine("")
                [void]$sb.AppendLine(" # Perform operations")
                [void]$sb.AppendLine(" }")
                [void]$sb.AppendLine("")
                [void]$sb.AppendLine(" #endregion Processing")
                [void]$sb.AppendLine("")
                [void]$sb.AppendLine(" # Complete progress")
                [void]$sb.AppendLine(" `$progressParams.Status = 'Completed'")
                [void]$sb.AppendLine(" `$progressParams.PercentComplete = 100")
                [void]$sb.AppendLine(' Write-Progress @progressParams -Completed')
                [void]$sb.AppendLine("")
                [void]$sb.AppendLine(' $duration = (Get-Date) - $script:StartTime')
                [void]$sb.AppendLine(' Write-Log "Script completed successfully in $($duration.TotalSeconds) seconds"')
                [void]$sb.AppendLine("}")
                [void]$sb.AppendLine("catch {")
                [void]$sb.AppendLine(' Write-Log "Error: $($_.Exception.Message)" -Level Error')
                [void]$sb.AppendLine(' Write-Log "Stack: $($_.ScriptStackTrace)" -Level Error')
                [void]$sb.AppendLine(" throw")
                [void]$sb.AppendLine("}")
                [void]$sb.AppendLine("finally {")
                [void]$sb.AppendLine(" # Cleanup")
                [void]$sb.AppendLine(' Write-Progress -Activity $script:ScriptName -Completed -ErrorAction SilentlyContinue')
                [void]$sb.AppendLine(" Stop-Transcript -ErrorAction SilentlyContinue | Out-Null")
                [void]$sb.AppendLine("")
                [void]$sb.AppendLine(' Write-Log "Script finished"')
                [void]$sb.AppendLine("}")
                [void]$sb.AppendLine("")
                [void]$sb.AppendLine("#endregion Main Logic")
            }
        }
    }

    end {
        Write-Debug "End '$($MyInvocation.MyCommand.Name)' at '$(Get-Date)'"
        return $sb.ToString()
    }
}