Private/monster_cleanup.ps1

# ==============================================================================
# MONSTER SCRIPT ENTERPRISE - CLEANUP PAYLOAD (MODULE EDITION)
# Файл: Private\monster_cleanup.ps1
# Назначение: Очистка временных файлов и памяти с поддержкой мультиязычной локализации
# ==============================================================================

[CmdletBinding()]
param(
    [switch]$TempFiles,
    [switch]$Memory,

    [Parameter(Mandatory = $false)]
    [ValidatePattern('^[a-zA-Z]{2}(-[a-zA-Z]{2,4})?$')]
    [string]$Language
)

# ------------------------------------------------------------------------------
# Автономный fallback для Write-Log
# ------------------------------------------------------------------------------

if (-not (Get-Command -Name Write-Log -ErrorAction SilentlyContinue)) {
    function Write-Log {
        param(
            [Parameter(Mandatory = $true)]
            [string]$Level,

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

            [string]$Context = 'GENERAL'
        )

        $timestamp = (Get-Date).ToString('yyyy-MM-dd HH:mm:ss')

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

        Write-Host `
            "[$timestamp] [$Level] [$Context] $Message" `
            -ForegroundColor $color
    }
}

# ------------------------------------------------------------------------------
# Определение директории скрипта
# ------------------------------------------------------------------------------

$scriptDir = $PSScriptRoot

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

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

# ------------------------------------------------------------------------------
# Подключение MonsterCore
# ------------------------------------------------------------------------------

$coreModulePath = Join-Path `
    -Path (Split-Path -Parent $scriptDir) `
    -ChildPath 'Private\MonsterCore.psm1'

if (-not (Test-Path -LiteralPath $coreModulePath -PathType Leaf)) {
    $coreModulePath = Join-Path `
        -Path $scriptDir `
        -ChildPath 'MonsterCore.psm1'
}

if (-not (Get-Command -Name Get-MonsterLocalization -ErrorAction SilentlyContinue)) {
    if (Test-Path -LiteralPath $coreModulePath -PathType Leaf) {
        try {
            Import-Module `
                -Name $coreModulePath `
                -Force `
                -ErrorAction Stop
        }
        catch {
            Write-Log `
                -Level 'ERROR' `
                -Message "Не удалось загрузить MonsterCore: $($_.Exception.Message)" `
                -Context 'CLEANUP'

            exit 1
        }
    }
}

# ------------------------------------------------------------------------------
# Установка языка
# ------------------------------------------------------------------------------

if (
    $Language -and
    (Get-Command -Name Set-MonsterLanguage -ErrorAction SilentlyContinue)
) {
    Set-MonsterLanguage -Language $Language
}

# ------------------------------------------------------------------------------
# Загрузка локализации
# ------------------------------------------------------------------------------

$msg = @{}

if (Get-Command -Name Get-MonsterLocalization -ErrorAction SilentlyContinue) {
    try {
        $msg = Get-MonsterLocalization `
            -ComponentName 'monster_cleanup' `
            -Language $Language
    }
    catch {
        Write-Log `
            -Level 'WARNING' `
            -Message "Не удалось загрузить локализацию: $($_.Exception.Message)" `
            -Context 'CLEANUP'
    }
}

# ------------------------------------------------------------------------------
# Локализованные сообщения с fallback-текстами
# ------------------------------------------------------------------------------

$txtInit = if ($msg.InitCleanup) {
    $msg.InitCleanup
}
else {
    'Инициализация подсистемы очистки...'
}

$txtTempStart = if ($msg.TempFilesStart) {
    $msg.TempFilesStart
}
else {
    'Очистка временных директорий системы...'
}

$txtTempDone = if ($msg.TempFilesSuccess) {
    $msg.TempFilesSuccess
}
else {
    'Временные файлы успешно удалены.'
}

$txtTempHost = if ($msg.OkTempFiles) {
    $msg.OkTempFiles
}
else {
    '[OK] Временные файлы очищены.'
}

$txtMemStart = if ($msg.MemoryStart) {
    $msg.MemoryStart
}
else {
    'Сборка мусора .NET и освобождение неиспользуемой памяти...'
}

$txtMemDone = if ($msg.MemorySuccess) {
    $msg.MemorySuccess
}
else {
    'Оперативная память оптимизирована.'
}

$txtMemHost = if ($msg.OkMemory) {
    $msg.OkMemory
}
else {
    '[OK] Память освобождена.'
}

$txtDefault = if ($msg.DefaultCleanup) {
    $msg.DefaultCleanup
}
else {
    'Выполнение стандартной очистки...'
}

$txtCritError = if ($msg.CritError) {
    $msg.CritError
}
else {
    'Критическая ошибка в подсистеме очистки: {0}'
}

$isVerbose = (
    $PSBoundParameters.ContainsKey('Verbose') -or
    $VerbosePreference -eq 'Continue'
)

Write-Log `
    -Level 'INFO' `
    -Message $txtInit `
    -Context 'CLEANUP'

# ------------------------------------------------------------------------------
# Основная логика
# ------------------------------------------------------------------------------

try {
    # --------------------------------------------------------------------------
    # Очистка временных файлов
    # --------------------------------------------------------------------------

    if ($TempFiles) {
        Write-Log `
            -Level 'INFO' `
            -Message $txtTempStart `
            -Context 'CLEANUP'

        $tempPaths = @(
            $env:TEMP
            (Join-Path -Path $env:SystemRoot -ChildPath 'Temp')
        ) |
            Where-Object {
                -not [string]::IsNullOrWhiteSpace($_)
            } |
            Select-Object -Unique

        $removedCount = 0
        $failedCount = 0

        foreach ($path in $tempPaths) {
            if (-not (Test-Path -LiteralPath $path -PathType Container)) {
                continue
            }

            $items = @(
                Get-ChildItem `
                    -LiteralPath $path `
                    -Recurse `
                    -Force `
                    -ErrorAction SilentlyContinue
            )

            foreach ($item in $items) {
                try {
                    Remove-Item `
                        -LiteralPath $item.FullName `
                        -Force `
                        -Recurse `
                        -ErrorAction Stop

                    $removedCount++
                }
                catch {
                    $failedCount++

                    if ($isVerbose) {
                        Write-Log `
                            -Level 'VERBOSE' `
                            -Message (
                                "Не удалось удалить объект [{0}]: {1}" -f
                                $item.FullName,
                                $_.Exception.Message
                            ) `
                            -Context 'CLEANUP'
                    }
                }
            }
        }

        if ($failedCount -gt 0) {
            Write-Log `
                -Level 'WARNING' `
                -Message (
                    "Очистка временных файлов завершена частично. " +
                    "Удалено: {0}, пропущено: {1}." -f
                    $removedCount,
                    $failedCount
                ) `
                -Context 'CLEANUP'
        }
        else {
            Write-Log `
                -Level 'SUCCESS' `
                -Message $txtTempDone `
                -Context 'CLEANUP'
        }

        Write-Host `
            $txtTempHost `
            -ForegroundColor Green
    }

    # --------------------------------------------------------------------------
    # Освобождение неиспользуемой памяти .NET
    # --------------------------------------------------------------------------

    if ($Memory) {
        Write-Log `
            -Level 'INFO' `
            -Message $txtMemStart `
            -Context 'CLEANUP'

        [System.GC]::Collect()
        [System.GC]::WaitForPendingFinalizers()
        [System.GC]::Collect()

        Write-Log `
            -Level 'SUCCESS' `
            -Message $txtMemDone `
            -Context 'CLEANUP'

        Write-Host `
            $txtMemHost `
            -ForegroundColor Green
    }

    # --------------------------------------------------------------------------
    # Режим без параметров
    # --------------------------------------------------------------------------

    if (-not $TempFiles -and -not $Memory) {
        Write-Log `
            -Level 'INFO' `
            -Message $txtDefault `
            -Context 'CLEANUP'
    }

    exit 0
}
catch {
    $criticalMessage = if ($msg.CritError) {
        $msg.CritError -f $_.Exception.Message
    }
    else {
        $txtCritError -f $_.Exception.Message
    }

    Write-Log `
        -Level 'CRITICAL' `
        -Message $criticalMessage `
        -Context 'CLEANUP'

    exit 1
}