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

$script:AnalyticsPath = Join-Path $env:LOCALAPPDATA "RescuePC\analytics"
$script:SessionFile = Join-Path $script:AnalyticsPath "sessions.json"
$script:ToolUsageFile = Join-Path $script:AnalyticsPath "tool_usage.json"
$script:SystemInfoFile = Join-Path $script:AnalyticsPath "system_info.json"

function Initialize-RescuePCAnalytics {

    if (-not (Test-Path $script:AnalyticsPath)) {
        New-Item -ItemType Directory -Path $script:AnalyticsPath -Force | Out-Null
    }

    if (-not (Test-Path $script:SystemInfoFile)) {
        $systemInfo = @{
            os_version = [System.Environment]::OSVersion.VersionString
            os_build = (Get-CimInstance -ClassName Win32_OperatingSystem).BuildNumber
            cpu_cores = [System.Environment]::ProcessorCount
            ram_gb = [math]::Round((Get-CimInstance -ClassName Win32_ComputerSystem).TotalPhysicalMemory / 1GB, 1)
            first_run = (Get-Date -Format "yyyy-MM-dd HH:mm:ss")
            install_id = [guid]::NewGuid().ToString()
        }
        $systemInfo | ConvertTo-Json | Set-Content $script:SystemInfoFile
    }
}

function Start-RescuePCSession {

    Initialize-RescuePCAnalytics

    $session = @{
        session_id = [guid]::NewGuid().ToString().Substring(0, 8)
        start_time = (Get-Date -Format "yyyy-MM-dd HH:mm:ss")
        end_time = $null
        tools_run = @()
        errors = @()
    }

    $script:CurrentSession = $session

    return $session.session_id
}

function Stop-RescuePCSession {

    if ($null -eq $script:CurrentSession) {
        return
    }

    $script:CurrentSession.end_time = (Get-Date -Format "yyyy-MM-dd HH:mm:ss")

    $sessions = @()
    if (Test-Path $script:SessionFile) {
        try {
            $existing = Get-Content $script:SessionFile -Raw | ConvertFrom-Json
            $sessions = @($existing)
        } catch {
            $sessions = @()
        }
    }

    $sessions += $script:CurrentSession

    if ($sessions.Count -gt 100) {
        $sessions = $sessions | Select-Object -Last 100
    }

    $sessions | ConvertTo-Json -Depth 10 | Set-Content $script:SessionFile

    $script:CurrentSession = $null
}

function Write-RescuePCToolUsage {

    param(
        [Parameter(Mandatory=$true)]
        [string]$ToolName,

        [bool]$Success = $true,

        [int]$Duration = 0,

        [string]$ErrorMessage = ""
    )

    Initialize-RescuePCAnalytics

    $usage = @{
        tool = $ToolName
        timestamp = (Get-Date -Format "yyyy-MM-dd HH:mm:ss")
        success = $Success
        duration_seconds = $Duration
        error = $ErrorMessage
    }

    if ($null -ne $script:CurrentSession) {
        $script:CurrentSession.tools_run += $usage
        if (-not $Success -and $ErrorMessage) {
            $script:CurrentSession.errors += $ErrorMessage
        }
    }

    $allUsage = @()
    if (Test-Path $script:ToolUsageFile) {
        try {
            $existing = Get-Content $script:ToolUsageFile -Raw | ConvertFrom-Json
            $allUsage = @($existing)
        } catch {
            $allUsage = @()
        }
    }

    $allUsage += $usage

    if ($allUsage.Count -gt 500) {
        $allUsage = $allUsage | Select-Object -Last 500
    }

    $allUsage | ConvertTo-Json -Depth 10 | Set-Content $script:ToolUsageFile
}

function Get-RescuePCStats {

    Initialize-RescuePCAnalytics

    $stats = @{
        total_sessions = 0
        total_tools_run = 0
        most_used_tools = @()
        success_rate = 0
        avg_session_duration = 0
        first_use = $null
        last_use = $null
    }

    if (Test-Path $script:SystemInfoFile) {
        $sysInfo = Get-Content $script:SystemInfoFile -Raw | ConvertFrom-Json
        $stats.first_use = $sysInfo.first_run
    }

    if (Test-Path $script:SessionFile) {
        try {
            $sessions = Get-Content $script:SessionFile -Raw | ConvertFrom-Json
            $stats.total_sessions = @($sessions).Count

            if ($stats.total_sessions -gt 0) {
                $lastSession = @($sessions) | Select-Object -Last 1
                $stats.last_use = $lastSession.start_time
            }
        } catch {}
    }

    if (Test-Path $script:ToolUsageFile) {
        try {
            $usage = Get-Content $script:ToolUsageFile -Raw | ConvertFrom-Json
            $usageArray = @($usage)
            $stats.total_tools_run = $usageArray.Count

            if ($stats.total_tools_run -gt 0) {
                $successful = ($usageArray | Where-Object { $_.success -eq $true }).Count
                $stats.success_rate = [math]::Round(($successful / $stats.total_tools_run) * 100, 1)

                $toolCounts = $usageArray | Group-Object -Property tool |
                    Sort-Object -Property Count -Descending |
                    Select-Object -First 5

                $stats.most_used_tools = $toolCounts | ForEach-Object {
                    @{
                        tool = $_.Name
                        count = $_.Count
                    }
                }
            }
        } catch {}
    }

    return $stats
}

function Show-RescuePCStats {

    $stats = Get-RescuePCStats

    Write-Host ""
    Write-Host "============================================" -ForegroundColor Cyan
    Write-Host "  RESCUEPC USAGE STATISTICS" -ForegroundColor Cyan
    Write-Host "============================================" -ForegroundColor Cyan
    Write-Host ""
    Write-Host "  Total Sessions:    $($stats.total_sessions)" -ForegroundColor White
    Write-Host "  Total Tools Run:   $($stats.total_tools_run)" -ForegroundColor White
    Write-Host "  Success Rate:      $($stats.success_rate)%" -ForegroundColor $(if ($stats.success_rate -ge 90) { "Green" } elseif ($stats.success_rate -ge 70) { "Yellow" } else { "Red" })
    Write-Host ""

    if ($stats.first_use) {
        Write-Host "  First Use:         $($stats.first_use)" -ForegroundColor Gray
    }
    if ($stats.last_use) {
        Write-Host "  Last Use:          $($stats.last_use)" -ForegroundColor Gray
    }
    Write-Host ""

    if ($stats.most_used_tools.Count -gt 0) {
        Write-Host "  Most Used Tools:" -ForegroundColor Cyan
        foreach ($tool in $stats.most_used_tools) {
            Write-Host "    - $($tool.tool): $($tool.count) times" -ForegroundColor White
        }
    }

    Write-Host ""
    Write-Host "  [All data stored locally - nothing sent online]" -ForegroundColor DarkGray
    Write-Host ""
}

function Clear-RescuePCAnalytics {

    if (Test-Path $script:AnalyticsPath) {
        Remove-Item -Path $script:AnalyticsPath -Recurse -Force
        Write-Host "[+] Analytics data cleared" -ForegroundColor Green
    }
}

Export-ModuleMember -Function @(
    'Initialize-RescuePCAnalytics',
    'Start-RescuePCSession',
    'Stop-RescuePCSession',
    'Write-RescuePCToolUsage',
    'Get-RescuePCStats',
    'Show-RescuePCStats',
    'Clear-RescuePCAnalytics'
)