Private/monster_apps_repair.ps1

# ==============================================================================
# MONSTER SCRIPT ENTERPRISE - APPS REPAIR PAYLOAD (MODULE EDITION)
# Файл: Private\monster_apps_repair.ps1
# Назначение: Восстановление UWP/AppX-пакетов с мультиязычной локализацией
# ==============================================================================

[CmdletBinding()]
param(
    [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' }
            '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 'APPS'

            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_apps_repair' `
            -Language $Language
    }
    catch {
        Write-Log `
            -Level 'WARNING' `
            -Message "Не удалось загрузить локализацию: $($_.Exception.Message)" `
            -Context 'APPS'
    }
}

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

$txtInit = if ($msg.InitApps) {
    $msg.InitApps
}
else {
    'Инициализация восстановления UWP/AppX-пакетов...'
}

$txtSearch = if ($msg.SearchApps) {
    $msg.SearchApps
}
else {
    'Получение списка зарегистрированных пакетов AppX...'
}

$txtNotFound = if ($msg.NotFound) {
    $msg.NotFound
}
else {
    'Зарегистрированные AppX-пакеты для восстановления не найдены.'
}

$txtVerboseRegister = if ($msg.VerboseRegister) {
    $msg.VerboseRegister
}
else {
    'Не удалось перерегистрировать пакет [{0}]: {1}'
}

$txtSuccess = if ($msg.SuccessDone) {
    $msg.SuccessDone
}
else {
    'Восстановление AppX-пакетов завершено. Успешно: {0}, ошибок: {1}.'
}

$txtModuleError = if ($msg.ModuleError) {
    $msg.ModuleError
}
else {
    'Не удалось загрузить модуль Appx: {0}'
}

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

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

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

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

try {
    # --------------------------------------------------------------------------
    # Загрузка модуля Appx
    # --------------------------------------------------------------------------

    try {
        if (-not (Get-Module -Name Appx -ErrorAction SilentlyContinue)) {
            Import-Module Appx -ErrorAction Stop
        }
    }
    catch {
        $moduleErrorMessage = [string]::Format(
            [System.Globalization.CultureInfo]::InvariantCulture,
            $txtModuleError,
            $_.Exception.Message
        )

        Write-Log `
            -Level 'ERROR' `
            -Message $moduleErrorMessage `
            -Context 'APPS'

        exit 1
    }

    # --------------------------------------------------------------------------
    # Получение списка пакетов
    # --------------------------------------------------------------------------

    Write-Log `
        -Level 'INFO' `
        -Message $txtSearch `
        -Context 'APPS'

    $packages = @(Get-AppxPackage -AllUsers -ErrorAction Stop)

    if ($packages.Count -eq 0) {
        Write-Log `
            -Level 'WARNING' `
            -Message $txtNotFound `
            -Context 'APPS'

        exit 0
    }

    $successCount = 0
    $failCount = 0

    # --------------------------------------------------------------------------
    # Перерегистрация пакетов
    # --------------------------------------------------------------------------

    foreach ($pkg in $packages) {
        try {
            if ([string]::IsNullOrWhiteSpace($pkg.InstallLocation)) {
                $failCount++
                continue
            }

            $manifestPath = Join-Path `
                -Path $pkg.InstallLocation `
                -ChildPath 'AppXManifest.xml'

            if (-not (Test-Path -LiteralPath $manifestPath -PathType Leaf)) {
                $failCount++
                continue
            }

            Add-AppxPackage `
                -DisableDevelopmentMode `
                -Register $manifestPath `
                -ErrorAction Stop |
                Out-Null

            $successCount++
        }
        catch {
            $failCount++

            if ($isVerbose) {
                $verboseMessage = [string]::Format(
                    [System.Globalization.CultureInfo]::InvariantCulture,
                    $txtVerboseRegister,
                    $pkg.Name,
                    $_.Exception.Message
                )

                Write-Log `
                    -Level 'DEBUG' `
                    -Message $verboseMessage `
                    -Context 'APPS'
            }
        }
    }

    # --------------------------------------------------------------------------
    # Итог
    # --------------------------------------------------------------------------

    $successMessage = [string]::Format(
        [System.Globalization.CultureInfo]::InvariantCulture,
        $txtSuccess,
        $successCount,
        $failCount
    )

    Write-Log `
        -Level 'SUCCESS' `
        -Message $successMessage `
        -Context 'APPS'

    exit 0
}
catch {
    $criticalMessage = [string]::Format(
        [System.Globalization.CultureInfo]::InvariantCulture,
        $txtCritError,
        $_.Exception.Message
    )

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

    exit 1
}