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

$Script:TelemetryEndpoint = "https://www.rescuepcrepairs.com/api/telemetry/report"
$Script:TelemetryQueue = @()
$Script:TelemetryEnabled = $true

function Send-ErrorTelemetry {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true)]
        [string]$ErrorCode,

        [Parameter(Mandatory=$true)]
        [string]$ErrorMessage,

        [Parameter(Mandatory=$true)]
        [string]$ModuleName,

        [Parameter(Mandatory=$true)]
        [ValidateSet("INFO", "WARNING", "ERROR", "CRITICAL")]
        [string]$Severity,

        [Parameter(Mandatory=$false)]
        [string]$StackTrace,

        [Parameter(Mandatory=$false)]
        [switch]$Async
    )

    if (-not $Script:TelemetryEnabled) {
        Write-Verbose "Telemetry disabled, skipping error report"
        return
    }

    $licenseKey = $global:LicenseKey
    if (-not $licenseKey) {
        $licenseKey = $env:RESCUEPC_LICENSE_KEY
    }
    if (-not $licenseKey) {
        Write-Verbose "No license key available, skipping telemetry"
        return
    }

    $usbFingerprint = $global:USBFingerprint
    if (-not $usbFingerprint) {
        $usbFingerprint = $env:RESCUEPC_USB_FINGERPRINT
    }

    $scrubbedMessage = $ErrorMessage
    $scrubbedStackTrace = $StackTrace

    if (Get-Command -Name Remove-PII -ErrorAction SilentlyContinue) {
        $scrubbedMessage = Remove-PII -Text $ErrorMessage
        if ($StackTrace) {
            $scrubbedStackTrace = Remove-PII -Text $StackTrace
        }
    }

    $osVersion = try {
        $os = Get-CimInstance -ClassName Win32_OperatingSystem -ErrorAction SilentlyContinue
        "$($os.Caption) $($os.Version)"
    } catch {
        "Unknown"
    }

    $appVersion = $global:AppVersion
    if (-not $appVersion) {
        $appVersion = "2.1.11"
    }

    $payload = @{
        licenseKey = $licenseKey
        errorCode = $ErrorCode
        errorMessage = $scrubbedMessage.Substring(0, [Math]::Min($scrubbedMessage.Length, 1000))
        moduleName = $ModuleName
        severity = $Severity
        osVersion = $osVersion
        appVersion = $appVersion
    }

    if ($usbFingerprint) {
        $payload.usbFingerprint = $usbFingerprint
    }

    if ($scrubbedStackTrace) {
        $payload.stackTrace = $scrubbedStackTrace.Substring(0, [Math]::Min($scrubbedStackTrace.Length, 5000))
    }

    if ($Async) {
        $Script:TelemetryQueue += $payload
        Write-Verbose "Queued error for batch telemetry: $ErrorCode"
        return
    }

    try {
        $json = $payload | ConvertTo-Json -Compress
        $response = Invoke-RestMethod -Uri $Script:TelemetryEndpoint -Method POST -Body $json -ContentType "application/json" -TimeoutSec 10 -ErrorAction Stop

        if ($response.success) {
            Write-Verbose "Telemetry sent: $ErrorCode (ID: $($response.errorId))"
        }
    } catch {
        Write-Verbose "Telemetry failed (non-critical): $($_.Exception.Message)"
    }
}

function Send-QueuedTelemetry {
    [CmdletBinding()]
    param()

    if ($Script:TelemetryQueue.Count -eq 0) {
        Write-Verbose "No queued telemetry to send"
        return
    }

    Write-Verbose "Sending $($Script:TelemetryQueue.Count) queued error reports..."

    foreach ($payload in $Script:TelemetryQueue) {
        try {
            $json = $payload | ConvertTo-Json -Compress
            Invoke-RestMethod -Uri $Script:TelemetryEndpoint -Method POST -Body $json -ContentType "application/json" -TimeoutSec 5 -ErrorAction Stop | Out-Null
        } catch {
        }
    }

    $Script:TelemetryQueue = @()
}

function Disable-Telemetry {
    $Script:TelemetryEnabled = $false
    Write-Verbose "Telemetry disabled"
}

function Enable-Telemetry {
    $Script:TelemetryEnabled = $true
    Write-Verbose "Telemetry enabled"
}

Export-ModuleMember -Function Send-ErrorTelemetry, Send-QueuedTelemetry, Disable-Telemetry, Enable-Telemetry