#Requires -Version 7.4

function Initialize-vSEALLogger {
    <#
    .SYNOPSIS
    Initializes the vSEAL logging subsystem for a given phase.

    .DESCRIPTION
    Configures streaming mode from the VSEAL_STREAM_MODE environment variable, extracts
    console and file log levels from the configuration, resolves the log output directory,
    and creates the initial NDJSON log file with a START entry containing phase, computer
    name, and PowerShell version metadata. After initialization, the logger is marked as
    active and an informational phase-start message is emitted.

    .PARAMETER Phase
    The execution phase to initialize logging for. Must be 'Seal', 'Engage', or 'Rollback'.

    .PARAMETER Configuration
    The parsed vSEAL configuration hashtable containing logging settings such as
    console_level, file_level, console_context, and phase-specific log paths.
    #>
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [ValidateSet('Seal', 'Engage', 'Rollback')]
        [string]$Phase,

        [Parameter(Mandatory)]
        [hashtable]$Configuration
    )

    # Initialize streaming configuration (before any logging)
    # Streaming mode enables NDJSON event emission for Go CLI communication
    $streamMode = $env:VSEAL_STREAM_MODE
    $script:StreamConfig.Mode = $streamMode
    $script:StreamConfig.Enabled = $streamMode -in @('stdout', 'stderr')
    $script:StreamConfig.OpId = [Guid]::NewGuid().ToString('N').Substring(0, 8)
    $script:StreamConfig.Phase = $Phase.ToLower()

    # Extract logging configuration with defaults
    $loggingConfig = $Configuration.logging
    if (-not $loggingConfig) { $loggingConfig = @{} }

    $script:LogConfig.ConsoleLevel = if ($loggingConfig.console_level) {
        $loggingConfig.console_level.ToUpper()
    } else {
        'INFO'
    }

    $script:LogConfig.FileLevel = if ($loggingConfig.file_level) {
        $loggingConfig.file_level.ToUpper()
    } else {
        'DEBUG'
    }

    $script:LogConfig.ConsoleContext = if ($loggingConfig.console_context) {
        $loggingConfig.console_context.ToLower()
    } else {
        'auto'
    }

    # Resolve log path
    $logPath = Resolve-vSEALLogPath -Phase $Phase -Configuration $Configuration
    $script:LogConfig.LogPath = $logPath

    # Build filename
    $timestamp = Get-Date -Format 'yyyyMMdd-HHmmss'
    $computerName = $env:COMPUTERNAME
    $logFileName = "vSEAL_${computerName}_${Phase}_$timestamp.log"
    $fullLogPath = Join-Path -Path $logPath -ChildPath $logFileName
    $script:LogConfig.LogFilePath = $fullLogPath

    # Create log file with START entry (replaces ps-jsonlogger New-Logger)
    $startEntry = [ordered]@{
        timestamp  = (Get-Date).ToString('o')
        level      = 'START'
        phase      = $Phase
        computer   = $computerName
        PSVersion  = $PSVersionTable.PSVersion.ToString()
    }

    $startJson = $startEntry | ConvertTo-Json -Compress
    Set-Content -Path $fullLogPath -Value $startJson -Encoding utf8

    # Mark as initialized
    $script:LoggerInitialized = $true

    Write-vSEALLog "Log file: $fullLogPath" -Level 'DEBUG'
}
