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',

            [string]$ComponentName = 'monster_apps_repair',

            [string]$Language = '',

            [object[]]$Arguments
        )

        $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 'CoreLoadError' `
                -ComponentName 'monster_apps_repair' `
                -Language $Language `
                -Arguments @($_.Exception.Message) `
                -Context 'APPS'

            exit 1
        }
    }
}

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

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

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

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

Write-Log `
    -Level 'INFO' `
    -Message 'InitApps' `
    -ComponentName 'monster_apps_repair' `
    -Language $Language `
    -Context 'APPS'

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

    try {
        if (-not (Get-Module -Name Appx -ErrorAction SilentlyContinue)) {
            Import-Module Appx -ErrorAction Stop
        }
    }
    catch {
        Write-Log `
            -Level 'ERROR' `
            -Message 'ModuleError' `
            -ComponentName 'monster_apps_repair' `
            -Language $Language `
            -Arguments @($_.Exception.Message) `
            -Context 'APPS'

        exit 1
    }

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

    Write-Log `
        -Level 'INFO' `
        -Message 'SearchApps' `
        -ComponentName 'monster_apps_repair' `
        -Language $Language `
        -Context 'APPS'

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

    if ($packages.Count -eq 0) {
        Write-Log `
            -Level 'WARNING' `
            -Message 'NotFound' `
            -ComponentName 'monster_apps_repair' `
            -Language $Language `
            -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) {
                Write-Log `
                    -Level 'DEBUG' `
                    -Message 'VerboseRegister' `
                    -ComponentName 'monster_apps_repair' `
                    -Language $Language `
                    -Arguments @($pkg.Name, $_.Exception.Message) `
                    -Context 'APPS'
            }
        }
    }

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

    Write-Log `
        -Level 'SUCCESS' `
        -Message 'SuccessDone' `
        -ComponentName 'monster_apps_repair' `
        -Language $Language `
        -Arguments @($successCount, $failCount) `
        -Context 'APPS'

    exit 0
}
catch {
    Write-Log `
        -Level 'CRITICAL' `
        -Message 'CritError' `
        -ComponentName 'monster_apps_repair' `
        -Language $Language `
        -Arguments @($_.Exception.Message) `
        -Context 'APPS'

    exit 1
}