Option Strict On
Option Explicit On

Imports System
Imports DrawingColor = System.Drawing.Color
Imports Nexamas.UI.Host
Imports Nexamas.UI.Theming
Imports SkiaSharp

Namespace Nexamas.UI.Quality

    ''' <summary>
    ''' Runtime proof that the host surface base clear is theme-aware across the
    ''' Skia render clear, WinForms transient background, and GL resize priming policy.
    ''' The gate intentionally checks the dark built-in theme so a hard-coded white
    ''' clear cannot satisfy the contract.
    ''' </summary>
    Friend NotInheritable Class MASHostSurfaceThemeAwareClearGate

        Private Const DarkThemeId As String = "dark-blue-night-sky-mas-signature"

        Private Sub New()
        End Sub

        Friend Shared Function Passes() As Boolean
            Return ProbeClearPolicyUsesThemeBackground() AndAlso
                   ProbeFallbackIsNeutralNotWhite() AndAlso
                   ProbeSurfaceControlBackColorFollowsPolicy()
        End Function

        Private Shared Function ProbeClearPolicyUsesThemeBackground() As Boolean
            Try
                ThemeManager.EnsureInitializedCore()

                Dim darkTheme As IMASAppTheme = ThemeManager.GetByIdCore(DarkThemeId)
                If darkTheme Is Nothing Then Return False

                Dim expected As SKColor = ExpectedBaseBackground(darkTheme)
                Dim actual As SKColor = MASSkiaHostSurfaceClearPolicy.ResolveForThemeOrFallback(darkTheme)

                If Not actual.Equals(expected) Then Return False
                If actual.Equals(SKColors.White) Then Return False

                Using host As New ThemeHost()
                    host.EnsureWithResolvedTheme(1.0F, darkTheme)
                    Dim fromContext As SKColor = MASSkiaHostSurfaceClearPolicy.ResolveForContextOrFallback(host.Context)
                    If Not fromContext.Equals(expected) Then Return False
                End Using

                Return True
            Catch ex As Exception
                Nexamas.UI.Diagnostics.MASExceptionSilencer.SwallowDiagnosticOnly(ex, "MASHostSurfaceThemeAwareClearGate.Policy")
                Return False
            End Try
        End Function

        Private Shared Function ProbeFallbackIsNeutralNotWhite() As Boolean
            Try
                Dim fallback As SKColor = MASSkiaHostSurfaceClearPolicy.FallbackClearColor
                Return fallback.Alpha = Byte.MaxValue AndAlso Not fallback.Equals(SKColors.White)
            Catch ex As Exception
                Nexamas.UI.Diagnostics.MASExceptionSilencer.SwallowDiagnosticOnly(ex, "MASHostSurfaceThemeAwareClearGate.Fallback")
                Return False
            End Try
        End Function

        Private Shared Function ProbeSurfaceControlBackColorFollowsPolicy() As Boolean
            Dim previousThemeId As String = Nothing

            Try
                ThemeManager.EnsureInitializedCore()
                previousThemeId = ThemeManager.CurrentCore.Id

                If Not ThemeManager.TryApplyThemeCore(DarkThemeId) Then Return False

                Dim darkTheme As IMASAppTheme = ThemeManager.GetByIdCore(DarkThemeId)
                If darkTheme Is Nothing Then Return False

                Dim expected As SKColor = ExpectedBaseBackground(darkTheme)
                Dim expectedDrawing As DrawingColor = MASSkiaHostSurfaceClearPolicy.ToDrawingColor(expected)

                Using surface As New MASSkiaHostSurfaceControl()
                    If Not surface.TransientClearColor.Equals(expected) Then Return False
                    If surface.BackColor.ToArgb() <> expectedDrawing.ToArgb() Then Return False

                    surface.SetTransientClearColor(New SKColor(12, 34, 56, 80))
                    If surface.TransientClearColor.Alpha <> Byte.MaxValue Then Return False
                    If surface.BackColor.ToArgb() <> DrawingColor.FromArgb(255, 12, 34, 56).ToArgb() Then Return False
                End Using

                Return True
            Catch ex As Exception
                Nexamas.UI.Diagnostics.MASExceptionSilencer.SwallowDiagnosticOnly(ex, "MASHostSurfaceThemeAwareClearGate.SurfaceControl")
                Return False
            Finally
                If Not String.IsNullOrWhiteSpace(previousThemeId) Then
                    Try
                        ThemeManager.TryApplyThemeCore(previousThemeId)
                    Catch restoreException As Exception
                        Nexamas.UI.Diagnostics.MASExceptionSilencer.SwallowDiagnosticOnly(restoreException, "MASHostSurfaceThemeAwareClearGate.RestoreTheme")
                    End Try
                End If
            End Try
        End Function

        Private Shared Function ExpectedBaseBackground(theme As IMASAppTheme) As SKColor
            Dim foundation As IMASThemeFoundation = MASAppThemeContracts.Foundation(theme)
            If foundation Is Nothing OrElse foundation.Background Is Nothing OrElse foundation.Background.Default Is Nothing Then
                Throw New InvalidOperationException("Theme does not provide a background default palette.")
            End If

            Return MASSkiaHostSurfaceClearPolicy.NormalizeOpaque(foundation.Background.Default.BaseBg)
        End Function

    End Class

End Namespace
