#Requires -Version 7.4

function Write-ConsoleLog {
    <#
    .SYNOPSIS
    Writes a color-coded log message to the console.

    .DESCRIPTION
    Formats and displays a timestamped log message using Write-Host with color-coding
    based on the log level. In stdout streaming mode (VSEAL_STREAM_MODE=stdout), all
    console output is suppressed to prevent polluting the NDJSON event stream. The
    context display behavior (caller information) is controlled by the Context parameter,
    which defaults to 'auto' (shown only for DEBUG, VERBOSE, ERROR, and FATAL levels).

    .PARAMETER Message
    The log message text to display.

    .PARAMETER Level
    The severity level that determines the output color. Valid values are DEBUG, VERBOSE,
    INFO, SUCCESS, WARNING, ERROR, and FATAL.

    .PARAMETER Context
    Controls when caller information is appended to the message. 'auto' shows context for
    diagnostic and error levels only, 'always' shows it unconditionally, 'never' hides it.
    Defaults to 'auto'.

    .PARAMETER CallerInfo
    Optional string identifying the caller, appended in parentheses when context display
    is active.
    #>
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [string]$Message,

        [Parameter(Mandatory)]
        [ValidateSet('DEBUG', 'VERBOSE', 'INFO', 'SUCCESS', 'WARNING', 'ERROR', 'FATAL')]
        [string]$Level,

        [ValidateSet('auto', 'always', 'never')]
        [string]$Context = 'auto',

        [string]$CallerInfo = ''
    )

    # Streaming mode check: suppress console output when streaming to stdout
    # In stdout mode, NDJSON events go to stdout - no Write-Host pollution
    # In stderr mode, events go to stderr and console output continues normally
    # NOTE: Check env var directly (not $script:StreamConfig) so this works in ThreadJobs
    # where the module is imported fresh without Initialize-vSEALLogger being called
    if ($env:VSEAL_STREAM_MODE -eq 'stdout') {
        return
    }

    # Color mapping
    $color = switch ($Level) {
        'DEBUG'   { 'Gray' }
        'VERBOSE' { 'DarkCyan' }
        'INFO'    { 'Cyan' }
        'SUCCESS' { 'Green' }
        'WARNING' { 'Yellow' }
        'ERROR'   { 'Red' }
        'FATAL'   { 'DarkRed' }
    }

    # Levels that show context in auto mode
    $contextLevels = @('DEBUG', 'VERBOSE', 'ERROR', 'FATAL')

    # Determine if context should be shown
    $showContext = switch ($Context) {
        'always' { $true }
        'never'  { $false }
        'auto'   { $Level -in $contextLevels }
    }

    # Format timestamp and level
    $timestamp = Get-Date -Format 'HH:mm:ss'
    $paddedLevel = $Level.PadRight(7)

    # Build output
    $output = "[$timestamp] [$paddedLevel] $Message"
    if ($showContext -and $CallerInfo) {
        $output += " ($CallerInfo)"
    }

    Write-Host $output -ForegroundColor $color
}
