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

function New-SupportBundle {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $false)]
        [string]$OutputPath
    )

    if (-not $OutputPath) {
        $timestamp = Get-Date -Format "yyyyMMdd_HHmmss"
        $OutputPath = Join-Path $env:USERPROFILE "Desktop\RescuePC_Support_$timestamp.zip"
    }

    $stagingDir = Join-Path $env:TEMP "RescuePC_Support_$(Get-Random)"
    New-Item -ItemType Directory -Path $stagingDir -Force | Out-Null

    try {
        Write-Host "📦 Generating RescuePC Support Bundle..." -ForegroundColor Cyan
        Write-Host ""

        Write-Host "  [1/7] Collecting system information..." -ForegroundColor Gray
        $systemSnapshot = @{
            Timestamp = (Get-Date).ToString("o")
            ComputerName = $env:COMPUTERNAME
            UserName = $env:USERNAME
            OSVersion = [System.Environment]::OSVersion.VersionString
            OSBuild = (Get-CimInstance Win32_OperatingSystem).BuildNumber
            Architecture = $env:PROCESSOR_ARCHITECTURE
            TotalRAM_GB = [math]::Round((Get-CimInstance Win32_ComputerSystem).TotalPhysicalMemory / 1GB, 2)
            AvailableRAM_GB = [math]::Round((Get-CimInstance Win32_OperatingSystem).FreePhysicalMemory / 1MB, 2)
            PowerShellVersion = $PSVersionTable.PSVersion.ToString()
            DotNetVersion = [System.Runtime.InteropServices.RuntimeInformation]::FrameworkDescription
            ExecutionPolicy = (Get-ExecutionPolicy).ToString()
        }
        $systemSnapshot | ConvertTo-Json -Depth 3 | Out-File (Join-Path $stagingDir "system_snapshot.json") -Encoding UTF8

        Write-Host "  [2/7] Collecting disk information..." -ForegroundColor Gray
        $diskInfo = Get-CimInstance Win32_LogicalDisk -Filter "DriveType=3" | ForEach-Object {
            @{
                Drive = $_.DeviceID
                FileSystem = $_.FileSystem
                Size_GB = [math]::Round($_.Size / 1GB, 2)
                FreeSpace_GB = [math]::Round($_.FreeSpace / 1GB, 2)
                PercentFree = if ($_.Size -gt 0) { [math]::Round(($_.FreeSpace / $_.Size) * 100, 1) } else { 0 }
            }
        }
        $diskInfo | ConvertTo-Json -Depth 3 | Out-File (Join-Path $stagingDir "disk_info.json") -Encoding UTF8

        Write-Host "  [3/7] Collecting repair logs..." -ForegroundColor Gray
        $logPaths = @(
            "C:\ProgramData\RescuePC\logs",
            "$env:LOCALAPPDATA\RescuePC\Logs",
            (Join-Path $PSScriptRoot "..\..\..\logs\repair_logs")
        )

        $repairLogs = @()
        foreach ($logPath in $logPaths) {
            if (Test-Path $logPath) {
                $logs = Get-ChildItem -Path $logPath -Filter "*.log" -ErrorAction SilentlyContinue |
                    Sort-Object LastWriteTime -Descending |
                    Select-Object -First 50
                foreach ($log in $logs) {
                    $repairLogs += @{
                        FileName = $log.Name
                        LastModified = $log.LastWriteTime.ToString("o")
                        Size_KB = [math]::Round($log.Length / 1KB, 2)
                        Content = (Get-Content $log.FullName -Raw -ErrorAction SilentlyContinue) -replace 'RESCUEPC-[A-Z0-9-]+', 'RESCUEPC-[REDACTED]'
                    }
                }
            }
        }
        if ($repairLogs.Count -gt 0) {
            $repairLogs | ConvertTo-Json -Depth 3 | Out-File (Join-Path $stagingDir "repair_history.json") -Encoding UTF8
        } else {
            @{ message = "No repair logs found" } | ConvertTo-Json | Out-File (Join-Path $stagingDir "repair_history.json") -Encoding UTF8
        }

        Write-Host "  [4/7] Collecting pack information..." -ForegroundColor Gray
        $packPaths = @(
            "$env:LOCALAPPDATA\RescuePC\Packs\Active\pack-manifest.json",
            (Join-Path $PSScriptRoot "..\..\repair\scripts\pack-manifest.json"),
            (Join-Path $PSScriptRoot "..\..\repair\repairs.manifest.json")
        )

        $packInfo = @{ found = $false }
        foreach ($packPath in $packPaths) {
            if (Test-Path $packPath) {
                try {
                    $manifest = Get-Content $packPath -Raw | ConvertFrom-Json
                    $packInfo = @{
                        found = $true
                        path = $packPath
                        version = $manifest.packVersion
                        repairCount = if ($manifest.repairs) { $manifest.repairs.Count } else { "N/A" }
                        generatedAt = $manifest.generatedAt
                    }
                    break
                } catch {
                    $packInfo = @{ found = $false; error = $_.Exception.Message }
                }
            }
        }
        $packInfo | ConvertTo-Json -Depth 3 | Out-File (Join-Path $stagingDir "pack_manifest.json") -Encoding UTF8

        Write-Host "  [5/7] Checking pack signature..." -ForegroundColor Gray
        $signaturePaths = @(
            "$env:LOCALAPPDATA\RescuePC\Packs\Active\pack-signature.json",
            (Join-Path $PSScriptRoot "..\..\repair\scripts\pack-signature.json")
        )

        $signatureInfo = @{ found = $false }
        foreach ($sigPath in $signaturePaths) {
            if (Test-Path $sigPath) {
                try {
                    $sig = Get-Content $sigPath -Raw | ConvertFrom-Json
                    $signatureInfo = @{
                        found = $true
                        path = $sigPath
                        algorithm = $sig.algorithm
                        signedAt = $sig.signedAt
                        signaturePresent = ($null -ne $sig.signature -and $sig.signature.Length -gt 0)
                    }
                    break
                } catch {
                    $signatureInfo = @{ found = $false; error = $_.Exception.Message }
                }
            }
        }
        $signatureInfo | ConvertTo-Json -Depth 3 | Out-File (Join-Path $stagingDir "pack_signature.json") -Encoding UTF8

        Write-Host "  [6/7] Collecting recent event logs..." -ForegroundColor Gray
        try {
            $events = @()
            $systemEvents = Get-WinEvent -LogName System -MaxEvents 50 -ErrorAction SilentlyContinue |
                Where-Object { $_.LevelDisplayName -in @('Error', 'Warning', 'Critical') } |
                Select-Object -First 25
            $appEvents = Get-WinEvent -LogName Application -MaxEvents 50 -ErrorAction SilentlyContinue |
                Where-Object { $_.LevelDisplayName -in @('Error', 'Warning', 'Critical') } |
                Select-Object -First 25

            foreach ($evt in ($systemEvents + $appEvents)) {
                $events += @{
                    TimeCreated = $evt.TimeCreated.ToString("o")
                    LogName = $evt.LogName
                    Level = $evt.LevelDisplayName
                    Source = $evt.ProviderName
                    EventId = $evt.Id
                    Message = ($evt.Message -split "`n")[0]
                }
            }
            $events | ConvertTo-Json -Depth 3 | Out-File (Join-Path $stagingDir "event_logs.json") -Encoding UTF8
        } catch {
            @{ error = "Could not collect event logs: $($_.Exception.Message)" } | ConvertTo-Json | Out-File (Join-Path $stagingDir "event_logs.json") -Encoding UTF8
        }

        Write-Host "  [7/7] Collecting configuration..." -ForegroundColor Gray
        $configInfo = @{
            LicenseTier = if ($global:LicenseTier) { $global:LicenseTier } else { "Unknown" }
            PackSignatureValid = if ($null -ne $global:PackSignatureValid) { $global:PackSignatureValid } else { "Unknown" }
            ScriptsRoot = if ($global:ScriptsRoot) { $global:ScriptsRoot } else { "Not set" }
            ModulesLoaded = (Get-Module | Where-Object { $_.Name -like "RescuePC*" } | Select-Object -ExpandProperty Name)
            BundleGeneratedAt = (Get-Date).ToString("o")
            BundleVersion = "1.0.0"
        }
        $configInfo | ConvertTo-Json -Depth 3 | Out-File (Join-Path $stagingDir "rescuepc_config.json") -Encoding UTF8

        Write-Host ""
        Write-Host "  Creating ZIP archive..." -ForegroundColor Gray

        if (Test-Path $OutputPath) {
            Remove-Item $OutputPath -Force
        }

        Compress-Archive -Path "$stagingDir\*" -DestinationPath $OutputPath -Force -CompressionLevel Optimal

        if (Test-Path $OutputPath) {
            $zipSize = [math]::Round((Get-Item $OutputPath).Length / 1KB, 2)
            Write-Host ""
            Write-Host "✅ Support bundle created successfully!" -ForegroundColor Green
            Write-Host "   📁 Location: $OutputPath" -ForegroundColor White
            Write-Host "   📊 Size: $zipSize KB" -ForegroundColor White
            Write-Host ""
            Write-Host "📧 Please send this file to: support@rescuepcrepairs.com" -ForegroundColor Cyan

            return $OutputPath
        } else {
            throw "Failed to create ZIP archive"
        }

    } catch {
        Write-Host ""
        Write-Host "❌ Error creating support bundle: $($_.Exception.Message)" -ForegroundColor Red
        return $null
    } finally {
        if (Test-Path $stagingDir) {
            Remove-Item $stagingDir -Recurse -Force -ErrorAction SilentlyContinue
        }
    }
}

function Test-RescuePCHealth {
    [CmdletBinding()]
    param()

    Write-Host ""
    Write-Host "🔍 RescuePC Health Check" -ForegroundColor Cyan
    Write-Host "========================" -ForegroundColor Cyan
    Write-Host ""

    $psVersion = $PSVersionTable.PSVersion
    $psOk = $psVersion.Major -ge 5
    Write-Host "  PowerShell Version: $psVersion " -NoNewline
    Write-Host $(if ($psOk) { "✅" } else { "⚠️ (5.1+ recommended)" }) -ForegroundColor $(if ($psOk) { "Green" } else { "Yellow" })

    $execPolicy = Get-ExecutionPolicy
    $execOk = $execPolicy -in @('Bypass', 'Unrestricted', 'RemoteSigned')
    Write-Host "  Execution Policy: $execPolicy " -NoNewline
    Write-Host $(if ($execOk) { "✅" } else { "⚠️ (May block scripts)" }) -ForegroundColor $(if ($execOk) { "Green" } else { "Yellow" })

    $isAdmin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
    Write-Host "  Running as Admin: $isAdmin " -NoNewline
    Write-Host $(if ($isAdmin) { "✅" } else { "⚠️ (Some repairs need admin)" }) -ForegroundColor $(if ($isAdmin) { "Green" } else { "Yellow" })

    $systemDrive = Get-CimInstance Win32_LogicalDisk -Filter "DeviceID='C:'"
    $freeGB = [math]::Round($systemDrive.FreeSpace / 1GB, 1)
    $diskOk = $freeGB -ge 5
    Write-Host "  Free Disk Space (C:): $freeGB GB " -NoNewline
    Write-Host $(if ($diskOk) { "✅" } else { "⚠️ (Low space)" }) -ForegroundColor $(if ($diskOk) { "Green" } else { "Yellow" })

    $freeRAM = [math]::Round((Get-CimInstance Win32_OperatingSystem).FreePhysicalMemory / 1MB, 1)
    $ramOk = $freeRAM -ge 1
    Write-Host "  Free RAM: $freeRAM GB " -NoNewline
    Write-Host $(if ($ramOk) { "✅" } else { "⚠️ (Low memory)" }) -ForegroundColor $(if ($ramOk) { "Green" } else { "Yellow" })

    $sigValid = $global:PackSignatureValid
    Write-Host "  Pack Signature Valid: $(if ($null -eq $sigValid) { 'Unknown' } else { $sigValid }) " -NoNewline
    Write-Host $(if ($sigValid -eq $true) { "✅" } elseif ($null -eq $sigValid) { "⚠️" } else { "❌" }) -ForegroundColor $(if ($sigValid -eq $true) { "Green" } elseif ($null -eq $sigValid) { "Yellow" } else { "Red" })

    Write-Host ""
    Write-Host "💡 Run 'New-SupportBundle' to generate a full diagnostic package." -ForegroundColor Gray
    Write-Host ""
}

Export-ModuleMember -Function New-SupportBundle, Test-RescuePCHealth