# RescuePC Protected Module - DO NOT EDIT
# Source code is maintained separately in the development repository.

function Get-SystemExecutable {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [ValidateSet('sfc','dism','chkdsk','sc.exe','powershell','cmd','reg','net','bcdedit')]
        [string]$Name
    )
    $system32 = Join-Path $env:SystemRoot 'System32'
    $sysnative = if ([Environment]::Is64BitOperatingSystem -and -not [Environment]::Is64BitProcess) {
        Join-Path $env:SystemRoot 'sysnative'
    } else {
        $system32
    }
    switch ($Name.ToLower()) {
        'sfc'      { return Join-Path $system32 'sfc.exe' }
        'dism'     { return Join-Path $system32 'dism.exe' }
        'chkdsk'   { return Join-Path $system32 'chkdsk.exe' }
        'sc.exe'   { return Join-Path $system32 'sc.exe' }
        'powershell' { return Join-Path $system32 'WindowsPowerShell\v1.0\powershell.exe' }
        'cmd'      { return Join-Path $system32 'cmd.exe' }
        'reg'      { return Join-Path $system32 'reg.exe' }
        'net'      { return Join-Path $system32 'net.exe' }
        'bcdedit'  { return Join-Path $system32 'bcdedit.exe' }
        default    { throw "Unknown system executable: $Name" }
    }
}

function Backup-RegistryKey {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [string]$KeyPath,

        [Parameter()]
        [string]$BackupFolder = "$env:TEMP\RescuePC_RegBackups"
    )

    if (-not (Test-Path -LiteralPath $BackupFolder)) {
        New-Item -Path $BackupFolder -ItemType Directory -Force | Out-Null
    }

    $safeName = $KeyPath -replace '[\\/:*?"<>|]', '_'
    $timestamp = Get-Date -Format 'yyyyMMdd_HHmmss'
    $backupFile = Join-Path $BackupFolder "regbackup_${safeName}_${timestamp}.reg"

    $regExe = Get-SystemExecutable -Name 'reg'
    $result = & $regExe export $KeyPath $backupFile /y 2>&1

    if ($LASTEXITCODE -eq 0) {
        Write-Host "[BACKUP] Registry key backed up: $backupFile" -ForegroundColor Green
        return $backupFile
    } else {
        Write-Warning "[BACKUP] Failed to backup registry key: $KeyPath - $result"
        return $null
    }
}

function Restore-RegistryKey {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [string]$BackupFile
    )

    if (-not (Test-Path -LiteralPath $BackupFile)) {
        Write-Error "[RESTORE] Backup file not found: $BackupFile"
        return $false
    }

    $regExe = Get-SystemExecutable -Name 'reg'
    $result = & $regExe import $BackupFile 2>&1

    if ($LASTEXITCODE -eq 0) {
        Write-Host "[RESTORE] Registry restored from: $BackupFile" -ForegroundColor Green
        return $true
    } else {
        Write-Error "[RESTORE] Failed to restore registry: $result"
        return $false
    }
}

function Clear-OldRegistryBackups {
    [CmdletBinding()]
    param(
        [Parameter()]
        [string]$BackupFolder = "$env:TEMP\RescuePC_RegBackups",

        [Parameter()]
        [int]$DaysToKeep = 7
    )

    if (-not (Test-Path -LiteralPath $BackupFolder)) {
        return
    }

    $cutoff = (Get-Date).AddDays(-$DaysToKeep)
    $oldFiles = Get-ChildItem -Path $BackupFolder -Filter "regbackup_*.reg" |
                Where-Object { $_.LastWriteTime -lt $cutoff }

    foreach ($file in $oldFiles) {
        Remove-Item -LiteralPath $file.FullName -Force -ErrorAction SilentlyContinue
    }

    if ($oldFiles.Count -gt 0) {
        Write-Host "[CLEANUP] Removed $($oldFiles.Count) old registry backups" -ForegroundColor Gray
    }
}

function Restart-ExplorerSafe {
    [CmdletBinding()]
    param(
        [Parameter()]
        [switch]$Force
    )

    if ($global:FixAllMode -and -not $Force) {
        Write-Host "[SKIP] Explorer restart deferred (Fix All mode)" -ForegroundColor Gray
        return $false
    }

    try {
        Stop-Process -Name "explorer" -Force -ErrorAction SilentlyContinue
        Start-Sleep -Seconds 2
        Start-Process -FilePath "$env:SystemRoot\explorer.exe" -ArgumentList "/n," -ErrorAction SilentlyContinue
        Write-Host "[OK] Explorer restarted" -ForegroundColor Green
        return $true
    } catch {
        Start-Process -FilePath "$env:SystemRoot\explorer.exe" -ArgumentList "/n," -ErrorAction SilentlyContinue
        Write-Host "[WARN] Explorer restart had issues" -ForegroundColor Yellow
        return $false
    }
}

Export-ModuleMember -Function Get-SystemExecutable, Backup-RegistryKey, Restore-RegistryKey, Clear-OldRegistryBackups, Restart-ExplorerSafe