Option Strict On
Option Explicit On

Imports System
Imports System.Collections.Generic
Imports System.Reflection
Imports Nexamas.UI.Application
Imports Nexamas.UI.Diagnostics

Namespace Nexamas.UI.Quality

    ''' <summary>
    ''' Commercial-readiness proof for the public diagnostics snapshot gateway.
    ''' </summary>
    ''' <remarks>
    ''' The gate proves that SDK consumers can read structured diagnostics through
    ''' MASApplication.Diagnostics without receiving Friend-owned runtime fault records,
    ''' mutable channels, or source-location details.
    ''' </remarks>
    Friend NotInheritable Class MASPublicDiagnosticsSnapshotGatewayGate

        Private Const ProbeContext As String = "MASPublicDiagnosticsSnapshotGatewayGate.PublicSnapshotProbe"

        Private Sub New()
        End Sub

        Friend Shared Function Passes() As Boolean
            Return EvaluateFindings().Count = 0
        End Function

        Friend Shared Function EvaluateFindings() As IReadOnlyList(Of MASCommercialReadinessFinding)
            Dim findings As New List(Of MASCommercialReadinessFinding)()

            If MASApplication.Diagnostics Is Nothing Then
                findings.Add(New MASCommercialReadinessFinding("diagnostics", "PublicSnapshotGateway", MASCommercialReadinessFindingSeverity.Error, "MASApplication.Diagnostics returned Nothing."))
                Return findings
            End If

            Try
                Using scope As New MASRuntimeFaultStrictModeScope(False, False, False)
                    MASExceptionSilencer.SwallowDiagnosticOnly(
                        New InvalidOperationException("Public diagnostics snapshot probe."),
                        ProbeContext)
                End Using
            Catch ex As Exception
                findings.Add(New MASCommercialReadinessFinding("diagnostics", "PublicSnapshotProbe", MASCommercialReadinessFindingSeverity.Error, "Public diagnostics probe could not record a safe runtime fault: " & ex.GetType().FullName))
                Return findings
            End Try

            Dim snapshot As MASApplicationDiagnosticsSnapshot = Nothing
            Try
                snapshot = MASApplication.Diagnostics.GetSnapshot(64)
            Catch ex As Exception
                findings.Add(New MASCommercialReadinessFinding("diagnostics", "PublicSnapshotRead", MASCommercialReadinessFindingSeverity.Error, "MASApplication.Diagnostics.GetSnapshot threw: " & ex.GetType().FullName))
                Return findings
            End Try

            If snapshot Is Nothing Then
                findings.Add(New MASCommercialReadinessFinding("diagnostics", "PublicSnapshotRead", MASCommercialReadinessFindingSeverity.Error, "MASApplication.Diagnostics.GetSnapshot returned Nothing."))
                Return findings
            End If

            If Not snapshot.IsReadOnlySnapshot Then
                findings.Add(New MASCommercialReadinessFinding("diagnostics", "PublicSnapshotReadOnly", MASCommercialReadinessFindingSeverity.Error, "Public diagnostics snapshot did not identify itself as read-only."))
            End If

            If snapshot.RecentFaults Is Nothing Then
                findings.Add(New MASCommercialReadinessFinding("diagnostics", "PublicRecentFaults", MASCommercialReadinessFindingSeverity.Error, "Public diagnostics snapshot did not expose a non-null recent-fault collection."))
                Return findings
            End If

            If snapshot.RetainedFaultCount <= 0 OrElse Not snapshot.HasFaults Then
                findings.Add(New MASCommercialReadinessFinding("diagnostics", "PublicFaultCount", MASCommercialReadinessFindingSeverity.Error, "Public diagnostics snapshot did not report retained runtime faults after a safe probe."))
            End If

            Dim foundProbe As Boolean = False
            For Each fault As MASApplicationDiagnosticsFaultSummary In snapshot.RecentFaults
                If fault Is Nothing Then Continue For

                If String.Equals(fault.Context, ProbeContext, StringComparison.Ordinal) Then
                    foundProbe = True

                    If Not String.Equals(fault.Severity, "Recoverable", StringComparison.Ordinal) Then
                        findings.Add(New MASCommercialReadinessFinding("diagnostics", "PublicFaultSeverity", MASCommercialReadinessFindingSeverity.Error, "Public diagnostics snapshot projected the probe severity incorrectly."))
                    End If

                    If Not String.Equals(fault.Category, "DiagnosticOnly", StringComparison.Ordinal) Then
                        findings.Add(New MASCommercialReadinessFinding("diagnostics", "PublicFaultCategory", MASCommercialReadinessFindingSeverity.Error, "Public diagnostics snapshot projected the probe category incorrectly."))
                    End If

                    If String.IsNullOrWhiteSpace(fault.ExceptionTypeName) OrElse String.IsNullOrWhiteSpace(fault.Message) Then
                        findings.Add(New MASCommercialReadinessFinding("diagnostics", "PublicFaultSummary", MASCommercialReadinessFindingSeverity.Error, "Public diagnostics snapshot did not expose safe exception summary data."))
                    End If
                End If
            Next

            If Not foundProbe Then
                findings.Add(New MASCommercialReadinessFinding("diagnostics", "PublicFaultVisibility", MASCommercialReadinessFindingSeverity.Error, "Public diagnostics snapshot did not include the safe fault probe in its recent window."))
            End If

            ValidateNoInternalRuntimeRecordLeak(findings)
            ValidateNoSourceLocationLeak(findings)

            Return findings
        End Function

        Private Shared Sub ValidateNoInternalRuntimeRecordLeak(findings As List(Of MASCommercialReadinessFinding))
            Dim recentProperty As PropertyInfo = GetType(MASApplicationDiagnosticsSnapshot).GetProperty("RecentFaults")
            If recentProperty Is Nothing Then
                findings.Add(New MASCommercialReadinessFinding("diagnostics", "PublicSnapshotShape", MASCommercialReadinessFindingSeverity.Error, "Public diagnostics snapshot is missing RecentFaults."))
                Return
            End If

            Dim propertyTypeName As String = recentProperty.PropertyType.FullName
            If propertyTypeName IsNot Nothing AndAlso propertyTypeName.IndexOf("MASRuntimeFaultRecord", StringComparison.Ordinal) >= 0 Then
                findings.Add(New MASCommercialReadinessFinding("diagnostics", "PublicInternalLeak", MASCommercialReadinessFindingSeverity.Error, "Public diagnostics snapshot exposes MASRuntimeFaultRecord in its public shape."))
            End If
        End Sub

        Private Shared Sub ValidateNoSourceLocationLeak(findings As List(Of MASCommercialReadinessFinding))
            Dim summaryType As Type = GetType(MASApplicationDiagnosticsFaultSummary)
            For Each propertyInfo As PropertyInfo In summaryType.GetProperties(BindingFlags.Instance Or BindingFlags.Public)
                If String.Equals(propertyInfo.Name, "SourceFile", StringComparison.OrdinalIgnoreCase) OrElse
                   String.Equals(propertyInfo.Name, "SourceLine", StringComparison.OrdinalIgnoreCase) OrElse
                   String.Equals(propertyInfo.Name, "FilePath", StringComparison.OrdinalIgnoreCase) OrElse
                   String.Equals(propertyInfo.Name, "LineNumber", StringComparison.OrdinalIgnoreCase) Then

                    findings.Add(New MASCommercialReadinessFinding("diagnostics", "PublicSourceLocationLeak", MASCommercialReadinessFindingSeverity.Error, "Public diagnostics fault summary exposes source-location detail: " & propertyInfo.Name))
                End If
            Next
        End Sub

    End Class

End Namespace
