Private/MonsterCore.psm1

# ==============================================================================
# MONSTER SCRIPT ENTERPRISE - CORE MODULE
# Файл: Private\MonsterCore.psm1
# Назначение: Инфраструктурный фундамент с абсолютной чистотой от хардкода
# ==============================================================================

$script:LogFile = $null
$script:LogContext = 'CORE'
$script:VerboseMode = $false
$script:ActiveLanguage = $null

function Get-MonsterScriptDir {
    $dir = $PSScriptRoot

    if (-not $dir -and $MyInvocation.MyCommand.Path) {
        $dir = Split-Path -Parent $MyInvocation.MyCommand.Path
    }

    if (-not $dir) {
        $dir = (Get-Location).Path
    }

    return $dir
}

# ------------------------------------------------------------------------------
# ПОДСИСТЕМА ЛОКАЛИЗАЦИИ И НОРМАЛИЗАЦИИ ЯЗЫКА (С ПОДДЕРЖКОЙ КАТЕГОРИЙ)
# ------------------------------------------------------------------------------

function Resolve-MonsterLanguageCode {
    param(
        [string]$RawLanguage
    )

    if ([string]::IsNullOrWhiteSpace($RawLanguage)) {
        if ($env:MONSTER_LANG) {
            $RawLanguage = $env:MONSTER_LANG
        }
        elseif ($script:ActiveLanguage) {
            $RawLanguage = $script:ActiveLanguage
        }
        else {
            $RawLanguage = $PSUICulture
        }
    }

    $clean = $RawLanguage.Trim().ToLowerInvariant()

    if ($clean -match '^([a-z]{2})') {
        $code = $Matches[1]
    }
    else {
        $code = 'en'
    }

    if ($code -eq 'uk') {
        $code = 'ua'
    }

    return $code
}

function Set-MonsterLanguage {
    param(
        [Parameter(Mandatory = $true)]
        [string]$Language
    )

    $normalized = Resolve-MonsterLanguageCode -RawLanguage $Language

    $script:ActiveLanguage = $normalized
    $env:MONSTER_LANG = $normalized
}

function Get-MonsterLocalization {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)]
        [string]$ComponentName,

        [string]$Language = '',

        [ValidateSet('main', 'logs')]
        [string]$Category = 'main'
    )

    $langCode = Resolve-MonsterLanguageCode -RawLanguage $Language
    $scriptDir = Get-MonsterScriptDir

    $moduleRoot = Split-Path -Parent $scriptDir
    $localesDir = Join-Path -Path $moduleRoot -ChildPath "Locales\$Category"

    if (-not (Test-Path -Path $localesDir -PathType Container)) {
        $localesDir = Join-Path -Path $scriptDir -ChildPath "Locales\$Category"
    }

    if (-not (Test-Path -Path $localesDir -PathType Container)) {
        $localesDir = Join-Path -Path $moduleRoot -ChildPath 'Locales'
        if (-not (Test-Path -Path $localesDir -PathType Container)) {
            $localesDir = Join-Path -Path $scriptDir -ChildPath 'Locales'
        }
    }

    $candidates = @(
        (Join-Path -Path $localesDir -ChildPath "$langCode\$ComponentName.psd1"),
        (Join-Path -Path $localesDir -ChildPath "en\$ComponentName.psd1"),
        (Join-Path -Path $localesDir -ChildPath "ru\$ComponentName.psd1")
    )

    foreach ($file in $candidates) {
        if (-not (Test-Path -Path $file -PathType Leaf)) {
            continue
        }

        try {
            $localeData = Import-PowerShellDataFile `
                -Path $file `
                -ErrorAction Stop

            if ($null -eq $localeData -or $localeData.Count -eq 0) {
                continue
            }

            return $localeData
        }
        catch {
            continue
        }

    }

    return @{}
}

# ------------------------------------------------------------------------------
# 1. ПОДСИСТЕМА ЛОГИРОВАНИЯ И EVENT VIEWER (CATEGORY: LOGS)
# ------------------------------------------------------------------------------

function Initialize-MonsterLogging {
    param(
        [Parameter(Mandatory = $true)]
        [string]$ScriptName,

        [switch]$VerboseLogging
    )

    $script:VerboseMode = $VerboseLogging
    $scriptDir = Get-MonsterScriptDir

    if ($scriptDir -like '*Program Files*') {
        $logsDir = Join-Path `
            -Path ([Environment]::GetFolderPath('LocalApplicationData')) `
            -ChildPath 'MonsterScript\Logs'
    }
    else {
        $moduleRoot = Split-Path `
            -Path (Split-Path -Path $scriptDir -Parent) `
            -Parent

        $logsDir = Join-Path -Path $moduleRoot -ChildPath 'Logs'

        if (-not (Test-Path -Path $logsDir -PathType Container)) {
            $logsDir = Join-Path -Path $scriptDir -ChildPath 'Logs'
        }
    }

    if (-not (Test-Path -Path $logsDir -PathType Container)) {
        try {
            New-Item `
                -ItemType Directory `
                -Path $logsDir `
                -Force `
                -ErrorAction Stop |
                Out-Null
        }
        catch {
            $logsDir = [System.IO.Path]::GetTempPath()
        }
    }

    $suffix = if ($script:VerboseMode) {
        '_verbose.log'
    }
    else {
        '.log'
    }

    $script:LogFile = Join-Path `
        -Path $logsDir `
        -ChildPath "$ScriptName$suffix"

    $sourceName = "Monster_$ScriptName"

    try {
        if (-not [System.Diagnostics.EventLog]::SourceExists($sourceName)) {
            New-EventLog `
                -LogName 'Monster' `
                -Source $sourceName `
                -ErrorAction Stop
        }
    }
    catch {
    }
}

function Write-Log {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)]
        [ValidateSet(
            'INFO',
            'SUCCESS',
            'WARNING',
            'ERROR',
            'CRITICAL',
            'VERBOSE',
            'DEBUG'
        )]
        [string]$Level,

        [Parameter(Mandatory = $true)]
        [string]$Message,

        [string]$Context = '',

        [string]$ComponentName = 'MonsterCore',

        [string]$Language = '',

        [object[]]$Arguments
    )

    if ($Message -notmatch '\s' -and $Message.Length -lt 50) {
        $locData = Get-MonsterLocalization -ComponentName $ComponentName -Language $Language -Category 'logs'
        if ($locData.ContainsKey($Message)) {
            $rawMsg = $locData[$Message]
            if ($null -ne $Arguments -and $Arguments.Count -gt 0) {
                $Message = $rawMsg -f $Arguments
            }
            else {
                $Message = $rawMsg
            }
        }
    }

    if ([string]::IsNullOrWhiteSpace($Context)) {
        if (
            -not [string]::IsNullOrWhiteSpace($script:LogContext) -and
            $script:LogContext -ne 'CORE'
        ) {
            $Context = $script:LogContext
        }
        else {
            try {
                $callStack = Get-PSCallStack

                $scriptFrame = $callStack |
                    Where-Object { $_.ScriptName } |
                    Select-Object -First 1

                if ($scriptFrame -and $scriptFrame.ScriptName) {
                    $Context = [System.IO.Path]::GetFileNameWithoutExtension(
                        $scriptFrame.ScriptName
                    ).ToUpperInvariant()
                }
                else {
                    $Context = 'CORE'
                }
            }
            catch {
                $Context = 'CORE'
            }
        }
    }

    if ($Level -eq 'VERBOSE' -and -not $script:VerboseMode) {
        return
    }

    $timestamp = (Get-Date).ToString('yyyy-MM-dd HH:mm:ss')
    $fileLogLine = "[$timestamp] [$Level] [$Context] $Message"

    if ($script:LogFile) {
        try {
            Add-Content `
                -Path $script:LogFile `
                -Value $fileLogLine `
                -Encoding UTF8 `
                -ErrorAction SilentlyContinue
        }
        catch {
        }
    }

    $tagColor = switch ($Level.ToUpperInvariant()) {
        'SUCCESS'  { 'Green' }
        'WARNING'  { 'Yellow' }
        'ERROR'    { 'Red' }
        'CRITICAL' { 'DarkRed' }
        'VERBOSE'  { 'Magenta' }
        'DEBUG'    { 'DarkGray' }
        default    { 'Cyan' }
    }

    Write-Host "[$timestamp] " -NoNewline -ForegroundColor DarkGray
    Write-Host "[$Level] " -NoNewline -ForegroundColor $tagColor
    Write-Host "[$Context] " -NoNewline -ForegroundColor DarkCyan

    if ($Level -eq 'CRITICAL') {
        Write-Host `
            $Message `
            -ForegroundColor White `
            -BackgroundColor DarkRed
    }
    else {
        Write-Host $Message
    }

    $sourceName = 'Monster_launcher'

    try {
        if ([System.Diagnostics.EventLog]::SourceExists($sourceName)) {
            $eventType = switch ($Level.ToUpperInvariant()) {
                'SUCCESS'  {
                    [System.Diagnostics.EventLogEntryType]::Information
                }
                'WARNING'  {
                    [System.Diagnostics.EventLogEntryType]::Warning
                }
                'ERROR'    {
                    [System.Diagnostics.EventLogEntryType]::Error
                }
                'CRITICAL' {
                    [System.Diagnostics.EventLogEntryType]::Error
                }
                default    {
                    [System.Diagnostics.EventLogEntryType]::Information
                }
            }

            if ($script:VerboseMode -or $Level -ne 'VERBOSE') {
                Write-EventLog `
                    -LogName 'Monster' `
                    -Source $sourceName `
                    -EventId 1000 `
                    -EntryType $eventType `
                    -Message "${Context}: $Message" `
                    -ErrorAction SilentlyContinue
            }
        }
    }
    catch {
    }
}

# ------------------------------------------------------------------------------
# 2. ИНТЕРАКТИВНЫЕ ДИАЛОГИ (REQUEST-USERCONSENT) — CATEGORY: MAIN
# ------------------------------------------------------------------------------

function Request-UserConsent {
    param(
        [Parameter(Mandatory = $true)]
        [string]$Message,

        [int]$TimeoutSeconds = 10,

        [bool]$DefaultActionIfTimeout = $false,

        [string]$ActionYesLabel = '',

        [string]$ActionNoLabel = '',

        [string]$Language = ''
    )

    $msg = Get-MonsterLocalization `
        -ComponentName 'MonsterCore' `
        -Language $Language `
        -Category 'main'

    if (-not $ActionYesLabel) {
        $ActionYesLabel = if ($msg.DefaultYes) { $msg.DefaultYes } else { '[DefaultYes key missing]' }
    }

    if (-not $ActionNoLabel) {
        $ActionNoLabel = if ($msg.DefaultNo) { $msg.DefaultNo } else { '[DefaultNo key missing]' }
    }

    if (-not [Environment]::UserInteractive) {
        Write-Log `
            -Level 'INFO' `
            -Message 'NonInteractiveDefault' `
            -ComponentName 'MonsterCore' `
            -Language $Language `
            -Arguments @($DefaultActionIfTimeout)

        return $DefaultActionIfTimeout
    }

    $noticeTitle = if ($msg.NoticeTitle) { $msg.NoticeTitle } else { '[NoticeTitle key missing]' }
    $yesText     = if ($msg.YesText)     { $msg.YesText }     else { '[YesText key missing]' }
    $noText      = if ($msg.NoText)      { $msg.NoText }      else { '[NoText key missing]' }

    Write-Host "`n==============================================" -ForegroundColor Yellow
    Write-Host " $noticeTitle" -ForegroundColor Yellow
    Write-Host '==============================================' -ForegroundColor Yellow
    Write-Host $Message -ForegroundColor White
    Write-Host '----------------------------------------------' -ForegroundColor Gray

    $defStr = if ($DefaultActionIfTimeout) { $yesText } else { $noText }

    $timeoutInfo = if ($msg.TimeoutInfo) {
        $msg.TimeoutInfo -f $TimeoutSeconds, $defStr
    }
    else {
        '[TimeoutInfo key missing]'
    }

    Write-Host $timeoutInfo -ForegroundColor DarkGray

    $pressKeys = if ($msg.PressKeys) {
        $msg.PressKeys -f $ActionYesLabel, $ActionNoLabel
    }
    else {
        '[PressKeys key missing]'
    }

    Write-Host $pressKeys -ForegroundColor Cyan

    $sw = [Diagnostics.Stopwatch]::StartNew()

    while ($sw.ElapsedMilliseconds -lt ($TimeoutSeconds * 1000)) {
        if ([Console]::KeyAvailable) {
            $key = [Console]::ReadKey($true)

            if ($key.Key -eq 'Y') {
                $choiceYes = if ($msg.UserChoiceYes) { $msg.UserChoiceYes } else { '[UserChoiceYes key missing]' }
                Write-Host "`n$choiceYes" -ForegroundColor Green
                return $true
            }

            if ($key.Key -eq 'N' -or $key.Key -eq 'Escape') {
                $choiceNo = if ($msg.UserChoiceNo) { $msg.UserChoiceNo } else { '[UserChoiceNo key missing]' }
                Write-Host "`n$choiceNo" -ForegroundColor Red
                return $false
            }
        }

        Start-Sleep -Milliseconds 100
    }

    $timeoutExpired = if ($msg.TimeoutExpired) {
        $msg.TimeoutExpired -f $defStr
    }
    else {
        '[TimeoutExpired key missing]'
    }

    Write-Host "`n$timeoutExpired" -ForegroundColor DarkYellow

    return $DefaultActionIfTimeout
}

# ------------------------------------------------------------------------------
# 3. ИНТЕЛЛЕКТУАЛЬНЫЕ ПРОВЕРКИ (DND & ACTIVE HOURS)
# ------------------------------------------------------------------------------

function Test-MonsterActiveHours {
    [CmdletBinding()]
    param(
        [string]$Language = ''
    )

    try {
        $currentHour = (Get-Date).Hour
        $startHour = $null
        $endHour = $null

        $policyPath = 'HKLM:\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate'

        if (Test-Path -Path $policyPath) {
            $pStart = (Get-ItemProperty -Path $policyPath -Name 'ActiveHoursStart' -ErrorAction SilentlyContinue).ActiveHoursStart
            $pEnd = (Get-ItemProperty -Path $policyPath -Name 'ActiveHoursEnd' -ErrorAction SilentlyContinue).ActiveHoursEnd

            if ($null -ne $pStart -and $null -ne $pEnd) {
                $startHour = [int]$pStart
                $endHour = [int]$pEnd
            }
        }

        if ($null -eq $startHour) {
            $uxPath = 'HKLM:\SOFTWARE\Microsoft\WindowsUpdate\UX\Settings'

            if (Test-Path -Path $uxPath) {
                $uStart = (Get-ItemProperty -Path $uxPath -Name 'ActiveHoursStart' -ErrorAction SilentlyContinue).ActiveHoursStart
                $uEnd = (Get-ItemProperty -Path $uxPath -Name 'ActiveHoursEnd' -ErrorAction SilentlyContinue).ActiveHoursEnd

                if ($null -ne $uStart -and $null -ne $uEnd) {
                    $startHour = [int]$uStart
                    $endHour = [int]$uEnd
                }
            }
        }

        if ($null -eq $startHour -or $null -eq $endHour) {
            return $false
        }

        if ($startHour -le $endHour) {
            return ($currentHour -ge $startHour -and $currentHour -lt $endHour)
        }

        return ($currentHour -ge $startHour -or $currentHour -lt $endHour)
    }
    catch {
        Write-Log `
            -Level 'VERBOSE' `
            -Message 'ActiveHoursError' `
            -ComponentName 'MonsterCore' `
            -Language $Language `
            -Arguments @($_.Exception.Message)

        return $false
    }
}

function Test-MonsterDndState {
    $isDndActive = $false

    try {
        $pathW11 = 'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Notifications\Settings'
        $dndVal = (Get-ItemProperty -Path $pathW11 -Name 'NOC_GLOBAL_SETTING_DND' -ErrorAction Stop).NOC_GLOBAL_SETTING_DND

        if ($dndVal -eq 1) {
            $isDndActive = $true
        }
    }
    catch {
    }

    if (-not $isDndActive) {
        try {
            $pathW10 = 'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\FocusAssist'
            $stateVal = (Get-ItemProperty -Path $pathW10 -Name 'State' -ErrorAction Stop).State

            if ($stateVal -gt 0) {
                $isDndActive = $true
            }
        }
        catch {
        }
    }

    return $isDndActive
}

# ------------------------------------------------------------------------------
# 4. ГЛАВНАЯ ФУНКЦИЯ ПРОВЕРКИ ОКРУЖЕНИЯ (ASSERT-MONSTERSAFETY)
# ------------------------------------------------------------------------------

function Assert-MonsterExecutionSafety {
    [CmdletBinding()]
    param(
        [switch]$IsAutoStart,

        [string]$Language = ''
    )

    $msg = Get-MonsterLocalization `
        -ComponentName 'MonsterCore' `
        -Language $Language `
        -Category 'main'

    $isInteractive = [Environment]::UserInteractive

    $isAdmin = (
        [Security.Principal.WindowsPrincipal](
            [Security.Principal.WindowsIdentity]::GetCurrent()
        )
    ).IsInRole(
        [Security.Principal.WindowsBuiltInRole]::Administrator
    )

    if (-not $isAdmin) {
        Write-Log `
            -Level 'CRITICAL' `
            -Message 'NoAdmin' `
            -ComponentName 'MonsterCore' `
            -Language $Language

        return $false
    }

    $triggerReschedule = {
        param(
            [int]$DelayMinutes = 60
        )

        $scriptDir = Get-MonsterScriptDir
        $managerScript = Join-Path -Path $scriptDir -ChildPath 'task_manager.ps1'

        if (-not (Test-Path -Path $managerScript -PathType Leaf)) {
            $managerScript = Join-Path -Path (Split-Path -Parent $scriptDir) -ChildPath 'Private\task_manager.ps1'
        }

        if (Test-Path -Path $managerScript -PathType Leaf) {
            Write-Log `
                -Level 'INFO' `
                -Message 'RescheduleReq' `
                -ComponentName 'MonsterCore' `
                -Language $Language `
                -Arguments @($DelayMinutes)

            & $managerScript -Reschedule -Minutes $DelayMinutes -Language $Language
        }
        else {
            Write-Log `
                -Level 'ERROR' `
                -Message 'ManagerNotFound' `
                -ComponentName 'MonsterCore' `
                -Language $Language `
                -Arguments @($managerScript)
        }
    }

    $isActiveHours = Test-MonsterActiveHours -Language $Language

    if ($isActiveHours) {
        Write-Log `
            -Level 'WARNING' `
            -Message 'ActiveHoursDetected' `
            -ComponentName 'MonsterCore' `
            -Language $Language

        if ($IsAutoStart -or -not $isInteractive) {
            Write-Log `
                -Level 'INFO' `
                -Message 'AutoRescheduleActiveHours' `
                -ComponentName 'MonsterCore' `
                -Language $Language

            & $triggerReschedule 60

            return $false
        }
        else {
            $promptText = if ($msg.ActiveHoursPrompt) { $msg.ActiveHoursPrompt } else { '[ActiveHoursPrompt key missing]' }
            $yesLabel   = if ($msg.ActiveHoursYes)    { $msg.ActiveHoursYes }    else { '[ActiveHoursYes key missing]' }
            $noLabel    = if ($msg.ActiveHoursNo)     { $msg.ActiveHoursNo }     else { '[ActiveHoursNo key missing]' }

            $consent = Request-UserConsent `
                -Message $promptText `
                -TimeoutSeconds 15 `
                -DefaultActionIfTimeout $false `
                -ActionYesLabel $yesLabel `
                -ActionNoLabel $noLabel `
                -Language $Language

            if (-not $consent) {
                Write-Log `
                    -Level 'INFO' `
                    -Message 'ActiveHoursCanceled' `
                    -ComponentName 'MonsterCore' `
                    -Language $Language

                return $false
            }

            Write-Log `
                -Level 'SUCCESS' `
                -Message 'MandateGranted' `
                -ComponentName 'MonsterCore' `
                -Language $Language

            return $true
        }
    }

    $isDndActive = Test-MonsterDndState

    if ($isDndActive) {
        Write-Log `
            -Level 'WARNING' `
            -Message 'DndDetected' `
            -ComponentName 'MonsterCore' `
            -Language $Language

        if ($IsAutoStart -or -not $isInteractive) {
            Write-Log `
                -Level 'INFO' `
                -Message 'AutoRescheduleDnd' `
                -ComponentName 'MonsterCore' `
                -Language $Language

            & $triggerReschedule 30

            return $false
        }
        else {
            $dndPrompt = if ($msg.DndPrompt) { $msg.DndPrompt } else { '[DndPrompt key missing]' }
            $dndYes    = if ($msg.DndYes)    { $msg.DndYes }    else { '[DndYes key missing]' }
            $dndNo     = if ($msg.DndNo)     { $msg.DndNo }     else { '[DndNo key missing]' }

            $consent = Request-UserConsent `
                -Message $dndPrompt `
                -TimeoutSeconds 15 `
                -DefaultActionIfTimeout $false `
                -ActionYesLabel $dndYes `
                -ActionNoLabel $dndNo `
                -Language $Language

            if (-not $consent) {
                Write-Log `
                    -Level 'INFO' `
                    -Message 'DndPostponed' `
                    -ComponentName 'MonsterCore' `
                    -Language $Language

                return $false
            }
        }
    }

    Write-Log `
        -Level 'SUCCESS' `
        -Message 'SafetyPassed' `
        -ComponentName 'MonsterCore' `
        -Language $Language

    return $true
}

Export-ModuleMember -Function `
    Initialize-MonsterLogging,
    Write-Log,
    Request-UserConsent,
    Test-MonsterActiveHours,
    Test-MonsterDndState,
    Assert-MonsterExecutionSafety,
    Set-MonsterLanguage,
    Get-MonsterLocalization,
    Resolve-MonsterLanguageCode