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 = ''
    )

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

    $moduleRoot = Split-Path -Parent $scriptDir
    $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 {
            return Import-PowerShellDataFile `
                -Path $file `
                -ErrorAction Stop
        }
        catch {
            continue
        }
    }

    return @{}
}

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

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 {
        # Для создания источника Event Viewer могут потребоваться права администратора.
    }
}

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 = ''
    )

    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)
# ------------------------------------------------------------------------------

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

    if (-not $ActionYesLabel) {
        $ActionYesLabel = if ($msg.DefaultYes) {
            $msg.DefaultYes
        }
        else {
            'Да (Y)'
        }
    }

    if (-not $ActionNoLabel) {
        $ActionNoLabel = if ($msg.DefaultNo) {
            $msg.DefaultNo
        }
        else {
            'Нет / Отмена (N)'
        }
    }

    if (-not [Environment]::UserInteractive) {
        $nonIntMsg = if ($msg.NonInteractiveDefault) {
            $msg.NonInteractiveDefault -f $DefaultActionIfTimeout
        }
        else {
            "Неинтерактивный режим. Автоматический выбор дефолта: $DefaultActionIfTimeout"
        }

        Write-Log `
            -Level 'INFO' `
            -Message $nonIntMsg `
            -Context 'CORE'

        return $DefaultActionIfTimeout
    }

    $noticeTitle = if ($msg.NoticeTitle) {
        $msg.NoticeTitle
    }
    else {
        '[MONSTER SYSTEM NOTICE]'
    }

    $yesText = if ($msg.YesText) {
        $msg.YesText
    }
    else {
        'ДА'
    }

    $noText = if ($msg.NoText) {
        $msg.NoText
    }
    else {
        'НЕТ'
    }

    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 {
        "Таймаут: $TimeoutSeconds сек. По умолчанию: $defStr"
    }

    Write-Host $timeoutInfo -ForegroundColor DarkGray

    $pressKeys = if ($msg.PressKeys) {
        $msg.PressKeys -f $ActionYesLabel, $ActionNoLabel
    }
    else {
        "Нажмите [Y] - $ActionYesLabel | [N] - $ActionNoLabel"
    }

    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 {
                    '[Выбор пользователя]: ДА'
                }

                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 {
                    '[Выбор пользователя]: НЕТ'
                }

                Write-Host "`n$choiceNo" -ForegroundColor Red
                return $false
            }
        }

        Start-Sleep -Milliseconds 100
    }

    $timeoutExpired = if ($msg.TimeoutExpired) {
        $msg.TimeoutExpired -f $defStr
    }
    else {
        "[Таймаут истёк]. Применён выбор по умолчанию: $defStr"
    }

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

    return $DefaultActionIfTimeout
}

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

function Test-MonsterActiveHours {
    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 "Ошибка при проверке Active Hours: $($_.Exception.Message)" `
            -Context 'CORE'

        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

    $isInteractive = [Environment]::UserInteractive

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

    if (-not $isAdmin) {
        $noAdminMsg = if ($msg.NoAdmin) {
            $msg.NoAdmin
        }
        else {
            'Скрипт запущен без прав администратора! Обслуживание системы невозможно.'
        }

        Write-Log `
            -Level 'CRITICAL' `
            -Message $noAdminMsg `
            -Context 'CORE'

        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) {
            $reschMsg = if ($msg.RescheduleReq) {
                $msg.RescheduleReq -f $DelayMinutes
            }
            else {
                "Запрос перепланирования Auto-задачи через task_manager.ps1 (сдвиг на $DelayMinutes минут)..."
            }

            Write-Log `
                -Level 'INFO' `
                -Message $reschMsg `
                -Context 'CORE'

            & $managerScript `
                -Reschedule `
                -Minutes $DelayMinutes `
                -Language $Language
        }
        else {
            $mgrNotFound = if ($msg.ManagerNotFound) {
                $msg.ManagerNotFound -f $managerScript
            }
            else {
                "Не найден task_manager.ps1 по пути: $managerScript"
            }

            Write-Log `
                -Level 'ERROR' `
                -Message $mgrNotFound `
                -Context 'CORE'
        }
    }

    $isActiveHours = Test-MonsterActiveHours

    if ($isActiveHours) {
        $actHourMsg = if ($msg.ActiveHoursDetected) {
            $msg.ActiveHoursDetected
        }
        else {
            'Обнаружены активные рабочие часы системы (Active Hours).'
        }

        Write-Log `
            -Level 'WARNING' `
            -Message $actHourMsg `
            -Context 'CORE'

        if ($IsAutoStart -or -not $isInteractive) {
            $autoActMsg = if ($msg.AutoRescheduleActiveHours) {
                $msg.AutoRescheduleActiveHours
            }
            else {
                'Автозапуск в активные часы. Отмена сеанса и перепланирование.'
            }

            Write-Log `
                -Level 'INFO' `
                -Message $autoActMsg `
                -Context 'CORE'

            & $triggerReschedule 60

            return $false
        }
        else {
            $promptText = if ($msg.ActiveHoursPrompt) {
                $msg.ActiveHoursPrompt
            }
            else {
                'Внимание! Сейчас идут активные часы системы. Вы хотите запустить обслуживание?'
            }

            $yesLabel = if ($msg.ActiveHoursYes) {
                $msg.ActiveHoursYes
            }
            else {
                'Принудительно начать'
            }

            $noLabel = if ($msg.ActiveHoursNo) {
                $msg.ActiveHoursNo
            }
            else {
                'Отменить'
            }

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

            if (-not $consent) {
                $abortMsg = if ($msg.ActiveHoursCanceled) {
                    $msg.ActiveHoursCanceled
                }
                else {
                    'Пользователь отменил запуск во время активных часов. Выход без перепланирования.'
                }

                Write-Log `
                    -Level 'INFO' `
                    -Message $abortMsg `
                    -Context 'CORE'

                return $false
            }

            $mandateMsg = if ($msg.MandateGranted) {
                $msg.MandateGranted
            }
            else {
                'Получено разрешение пользователя на запуск во время активных часов.'
            }

            Write-Log `
                -Level 'SUCCESS' `
                -Message $mandateMsg `
                -Context 'CORE'

            return $true
        }
    }

    $isDndActive = Test-MonsterDndState

    if ($isDndActive) {
        $dndDetMsg = if ($msg.DndDetected) {
            $msg.DndDetected
        }
        else {
            'Обнаружен активный режим концентрации (DND / Focus Assist).'
        }

        Write-Log `
            -Level 'WARNING' `
            -Message $dndDetMsg `
            -Context 'CORE'

        if ($IsAutoStart -or -not $isInteractive) {
            $autoDndMsg = if ($msg.AutoRescheduleDnd) {
                $msg.AutoRescheduleDnd
            }
            else {
                'Автозапуск при активном DND. Отмена сеанса и перепланирование.'
            }

            Write-Log `
                -Level 'INFO' `
                -Message $autoDndMsg `
                -Context 'CORE'

            & $triggerReschedule 30

            return $false
        }
        else {
            $dndPrompt = if ($msg.DndPrompt) {
                $msg.DndPrompt
            }
            else {
                'Внимание! В системе включен режим DND (концентрация/игра). Запустить очистку?'
            }

            $dndYes = if ($msg.DndYes) {
                $msg.DndYes
            }
            else {
                'Запустить всё равно'
            }

            $dndNo = if ($msg.DndNo) {
                $msg.DndNo
            }
            else {
                'Отложить'
            }

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

            if (-not $consent) {
                $dndPostpone = if ($msg.DndPostponed) {
                    $msg.DndPostponed
                }
                else {
                    'Пользователь отложил запуск из-за DND. Выход без перепланирования.'
                }

                Write-Log `
                    -Level 'INFO' `
                    -Message $dndPostpone `
                    -Context 'CORE'

                return $false
            }
        }
    }

    $passedMsg = if ($msg.SafetyPassed) {
        $msg.SafetyPassed
    }
    else {
        'Все проверки безопасности и окружения успешно пройдены.'
    }

    Write-Log `
        -Level 'SUCCESS' `
        -Message $passedMsg `
        -Context 'CORE'

    return $true
}

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