Option Strict On
Option Explicit On

Imports System
Imports System.Collections.Generic
Imports System.Globalization
Imports System.IO
Imports Nexamas.UI.Architecture
Imports Nexamas.UI.Application
Imports Nexamas.UI.Layout
Imports Nexamas.UI.Localization
Imports Nexamas.UI.Output
Imports Nexamas.UI.Performance
Imports Nexamas.UI.Verification

Namespace Nexamas.UI.Certification

    ''' <summary>
    ''' Central internal orchestrator for lightweight Nexamas UI quality gates.
    ''' </summary>
    ''' <remarks>
    ''' The orchestrator intentionally runs only read-only, deterministic, non-visual gates. It does not capture
    ''' screenshots, approve baselines, allocate UI controls, schedule frames, mutate diagnostics, or expose public telemetry.
    ''' Heavy CI/build/runtime probes remain owned by tools/quality and eng/ci scripts.
    ''' </remarks>
    Friend NotInheritable Class MASQualityOrchestrator
        Private Const RunId As String = "MAS-QUALITY-ORCHESTRATOR-2026-07-01"

        Private Sub New()
        End Sub

        Friend Shared Function Run() As MASQualityReport
            Return Run(projectRoot:=Nothing)
        End Function

        Friend Shared Function Run(projectRoot As String) As MASQualityReport
            Dim results As New List(Of MASQualityGateResult)()

            results.Add(CreateSelfRegistrationResult())
            results.Add(RunAssetPresenceGate(projectRoot))
            results.Add(RunArchitectureValidationGate())
            results.Add(RunApplicationOwnershipClosureGate())
            results.Add(RunSizeLayoutElementClosureGate())
            results.Add(RunRenderHitBoundsClosureGate())
            results.Add(RunLocalizationRuntimeOwnershipGate())
            results.Add(RunOutputApplicationRouteGate())
            results.Add(RunComponentCoverageGate())
            results.Add(RunRenderVerificationCoverageGate())
            results.Add(RunRenderVerificationElementCoverageClosureGate())
            results.Add(RunDeadPathClosureGate(projectRoot))
            results.Add(RunSizeLayoutRuntimeVerificationGate())
            results.Add(RunPerformanceDiagnosticsOrchestrationGate())
            results.Add(RunRenderVerificationReadinessGate())
            results.Add(RunSurfaceMaterialProofGate())
            results.Add(RunCertificationOrchestrationClosureGate(results))

            Return New MASQualityReport(RunId, Nexamas.UI.Timing.MASTimeProvider.UtcNow(), results)
        End Function

        Private Shared Function CreateSelfRegistrationResult() As MASQualityGateResult
            Return MASQualityGateResult.Passed(
                gateKey:="quality-orchestrator",
                displayName:="Quality Orchestrator Registration",
                ownerName:="CertificationSystem",
                certificationSystemKey:="quality-orchestrator",
                summary:="The Quality Orchestrator is registered as the central lightweight evidence aggregator for certification gates.",
                details:=New String() {"Aggregates asset presence, architecture validation, Application ownership closure, Size/Layout element closure, render/hit-bounds closure, Localization / RTL runtime ownership, Output product route closure, component coverage, render-verification coverage, Render Verification element coverage closure, dead-path closure, Size/Layout runtime verification, render-verification readiness, and surface-material proof gates."})
        End Function

        Private Shared Function RunAssetPresenceGate(projectRoot As String) As MASQualityGateResult
            Dim root As String = ResolveProjectRoot(projectRoot)
            If String.IsNullOrWhiteSpace(root) Then
                Return MASQualityGateResult.Skipped(
                    gateKey:="quality-asset-presence",
                    displayName:="Quality Asset Presence Gate",
                    ownerName:="CertificationSystem",
                    certificationSystemKey:="quality-asset-presence",
                    summary:="The repository root was not available in the current runtime context, so asset presence remains delegated to tools/quality.",
                    details:=New String() {"Run tools/quality/Run-NexamasUIQuality.ps1 from the repository root for a blocking file-system proof."})
            End If

            Try
                Dim report As MASQualityAssetPresenceReport = MASQualityAssetPresenceGate.Evaluate(root)
                If report.HasMissingAssets Then
                    Return MASQualityGateResult.Failed(
                        gateKey:="quality-asset-presence",
                        displayName:="Quality Asset Presence Gate",
                        ownerName:="CertificationSystem",
                        certificationSystemKey:="quality-asset-presence",
                        errorCount:=report.MissingAssetCount,
                        warningCount:=0,
                        summary:=report.MissingAssetCount.ToString(CultureInfo.InvariantCulture) & " required asset(s) are missing from the product tree.",
                        details:=report.CreateMissingAssetList())
                End If

                Return MASQualityGateResult.Passed(
                    gateKey:="quality-asset-presence",
                    displayName:="Quality Asset Presence Gate",
                    ownerName:="CertificationSystem",
                    certificationSystemKey:="quality-asset-presence",
                    summary:=report.RequiredAssetCount.ToString(CultureInfo.InvariantCulture) & " required project and quality assets are present.",
                    details:=New String() {"Project root: " & root})
            Catch ex As Exception
                Return MASQualityGateResult.Failed(
                    gateKey:="quality-asset-presence",
                    displayName:="Quality Asset Presence Gate",
                    ownerName:="CertificationSystem",
                    certificationSystemKey:="quality-asset-presence",
                    errorCount:=1,
                    warningCount:=0,
                    summary:="Asset presence evaluation failed before certification evidence could be trusted.",
                    details:=New String() {If(ex.Message, String.Empty)})
            End Try
        End Function

        Private Shared Function RunArchitectureValidationGate() As MASQualityGateResult
            Try
                Dim validation As MASArchitectureValidationResult = MASArchitectureValidator.Validate()
                Dim errors As Integer = 0
                Dim warnings As Integer = 0
                Dim details As New List(Of String)()

                If validation IsNot Nothing AndAlso validation.Issues IsNot Nothing Then
                    For Each issue As MASArchitectureValidationIssue In validation.Issues
                        If issue Is Nothing Then Continue For
                        If issue.Severity = MASArchitectureValidationSeverity.Error Then errors += 1
                        If issue.Severity = MASArchitectureValidationSeverity.Warning Then warnings += 1
                        If details.Count < 24 Then details.Add(issue.ToString())
                    Next
                End If

                If errors > 0 Then
                    Return MASQualityGateResult.Failed(
                        gateKey:="architecture-validation",
                        displayName:="Architecture Registry Validation",
                        ownerName:="ArchitectureSystem",
                        certificationSystemKey:="final-architecture-closure",
                        errorCount:=errors,
                        warningCount:=warnings,
                        summary:=errors.ToString(CultureInfo.InvariantCulture) & " architecture error(s) were found in the registered component catalog.",
                        details:=details)
                End If

                If warnings > 0 Then
                    Return MASQualityGateResult.PassedWithWarnings(
                        gateKey:="architecture-validation",
                        displayName:="Architecture Registry Validation",
                        ownerName:="ArchitectureSystem",
                        certificationSystemKey:="final-architecture-closure",
                        warningCount:=warnings,
                        summary:=warnings.ToString(CultureInfo.InvariantCulture) & " architecture warning(s) remain under monitoring.",
                        details:=details)
                End If

                Return MASQualityGateResult.Passed(
                    gateKey:="architecture-validation",
                    displayName:="Architecture Registry Validation",
                    ownerName:="ArchitectureSystem",
                    certificationSystemKey:="final-architecture-closure",
                    summary:="The registered component architecture catalog has no blocking validation issues.",
                    details:=New String() {"MASArchitectureValidator.Validate completed without errors or warnings."})
            Catch ex As Exception
                Return MASQualityGateResult.Failed(
                    gateKey:="architecture-validation",
                    displayName:="Architecture Registry Validation",
                    ownerName:="ArchitectureSystem",
                    certificationSystemKey:="final-architecture-closure",
                    errorCount:=1,
                    warningCount:=0,
                    summary:="Architecture validation threw before completing the catalog proof.",
                    details:=New String() {If(ex.Message, String.Empty)})
            End Try
        End Function


        Private Shared Function RunApplicationOwnershipClosureGate() As MASQualityGateResult
            Try
                Dim report As MASApplicationOwnershipClosureReport = MASApplicationOwnershipClosureAudit.VerifyCurrent()
                If report Is Nothing OrElse Not report.IsClosed Then
                    Dim errorCount As Integer = If(report Is Nothing, 1, Math.Max(1, report.ErrorCount))
                    Dim details As IReadOnlyList(Of String) = New String() {"Application ownership closure audit returned no report."}
                    If report IsNot Nothing Then details = report.CreateFindingDetails(32)

                    Return MASQualityGateResult.Failed(
                        gateKey:="application-ownership-closure",
                        displayName:="Application Ownership Closure Gate",
                        ownerName:="ApplicationSystem / SizeLayoutSystem / CertificationSystem",
                        certificationSystemKey:="application-ownership-closure",
                        errorCount:=errorCount,
                        warningCount:=If(report Is Nothing, 0, report.WarningCount),
                        summary:="Application control admission, retained layout ownership, or raw geometry mutation routes are not fully closed.",
                        details:=details)
                End If

                If report.WarningCount > 0 Then
                    Return MASQualityGateResult.PassedWithWarnings(
                        gateKey:="application-ownership-closure",
                        displayName:="Application Ownership Closure Gate",
                        ownerName:="ApplicationSystem / SizeLayoutSystem / CertificationSystem",
                        certificationSystemKey:="application-ownership-closure",
                        warningCount:=report.WarningCount,
                        summary:=report.Summary,
                        details:=report.CreateSummaryDetails())
                End If

                Return MASQualityGateResult.Passed(
                    gateKey:="application-ownership-closure",
                    displayName:="Application Ownership Closure Gate",
                    ownerName:="ApplicationSystem / SizeLayoutSystem / CertificationSystem",
                    certificationSystemKey:="application-ownership-closure",
                    summary:=report.Summary,
                    details:=report.CreateSummaryDetails())
            Catch ex As Exception
                Return MASQualityGateResult.Failed(
                    gateKey:="application-ownership-closure",
                    displayName:="Application Ownership Closure Gate",
                    ownerName:="ApplicationSystem / SizeLayoutSystem / CertificationSystem",
                    certificationSystemKey:="application-ownership-closure",
                    errorCount:=1,
                    warningCount:=0,
                    summary:="Application ownership closure audit threw before completing the ownership proof.",
                    details:=New String() {If(ex.Message, String.Empty)})
            End Try
        End Function




        Private Shared Function RunLocalizationRuntimeOwnershipGate() As MASQualityGateResult
            Try
                Dim report As MASLocalizationRuntimeOwnershipReport = MASLocalizationRuntimeOwnershipAudit.VerifyCurrent()
                If report Is Nothing OrElse Not report.IsClosed Then
                    Dim errorCount As Integer = If(report Is Nothing, 1, Math.Max(1, report.ErrorCount))
                    Dim details As IReadOnlyList(Of String) = New String() {"Localization / RTL runtime ownership audit returned no report."}
                    If report IsNot Nothing Then details = report.CreateFindingDetails(32)

                    Return MASQualityGateResult.Failed(
                        gateKey:="localization-runtime-ownership",
                        displayName:="Localization / RTL Runtime Ownership Gate",
                        ownerName:="LocalizationSystem / CertificationSystem",
                        certificationSystemKey:="localization-runtime-ownership",
                        errorCount:=errorCount,
                        warningCount:=If(report Is Nothing, 0, report.WarningCount),
                        summary:="Localization / RTL is not fully closed against runtime text ownership, RTL culture facts, or public host-route boundary rules.",
                        details:=details)
                End If

                If report.WarningCount > 0 Then
                    Return MASQualityGateResult.PassedWithWarnings(
                        gateKey:="localization-runtime-ownership",
                        displayName:="Localization / RTL Runtime Ownership Gate",
                        ownerName:="LocalizationSystem / CertificationSystem",
                        certificationSystemKey:="localization-runtime-ownership",
                        warningCount:=report.WarningCount,
                        summary:=report.Summary,
                        details:=report.CreateSummaryDetails())
                End If

                Return MASQualityGateResult.Passed(
                    gateKey:="localization-runtime-ownership",
                    displayName:="Localization / RTL Runtime Ownership Gate",
                    ownerName:="LocalizationSystem / CertificationSystem",
                    certificationSystemKey:="localization-runtime-ownership",
                    summary:=report.Summary,
                    details:=report.CreateSummaryDetails())
            Catch ex As Exception
                Return MASQualityGateResult.Failed(
                    gateKey:="localization-runtime-ownership",
                    displayName:="Localization / RTL Runtime Ownership Gate",
                    ownerName:="LocalizationSystem / CertificationSystem",
                    certificationSystemKey:="localization-runtime-ownership",
                    errorCount:=1,
                    warningCount:=0,
                    summary:="Localization / RTL runtime ownership audit threw before completing the runtime text and RTL boundary proof.",
                    details:=New String() {If(ex.Message, String.Empty)})
            End Try
        End Function


        Private Shared Function RunOutputApplicationRouteGate() As MASQualityGateResult
            Try
                Dim report As MASOutputApplicationRouteReport = MASOutputApplicationRouteAudit.VerifyCurrent()
                If report Is Nothing OrElse Not report.IsClosed Then
                    Dim errorCount As Integer = If(report Is Nothing, 1, Math.Max(1, report.ErrorCount))
                    Dim details As IReadOnlyList(Of String) = New String() {"Output product route audit returned no report."}
                    If report IsNot Nothing Then details = report.CreateFindingDetails(32)

                    Return MASQualityGateResult.Failed(
                        gateKey:="output-application-route",
                        displayName:="Output Product Route Gate",
                        ownerName:="ApplicationSystem / OutputSystem / CertificationSystem",
                        certificationSystemKey:="output-application-route",
                        errorCount:=errorCount,
                        warningCount:=If(report Is Nothing, 0, report.WarningCount),
                        summary:="Output is not fully productized against the public Application-owned facade, formal capability catalog, internally governed Chart/Report/Render Verification foundations, and product evidence bundle route.",
                        details:=details)
                End If

                If report.WarningCount > 0 Then
                    Return MASQualityGateResult.PassedWithWarnings(
                        gateKey:="output-application-route",
                        displayName:="Output Product Route Gate",
                        ownerName:="ApplicationSystem / OutputSystem / CertificationSystem",
                        certificationSystemKey:="output-application-route",
                        warningCount:=report.WarningCount,
                        summary:=report.Summary,
                        details:=report.CreateSummaryDetails())
                End If

                Return MASQualityGateResult.Passed(
                    gateKey:="output-application-route",
                    displayName:="Output Product Route Gate",
                    ownerName:="ApplicationSystem / OutputSystem / CertificationSystem",
                    certificationSystemKey:="output-application-route",
                    summary:=report.Summary,
                    details:=report.CreateSummaryDetails())
            Catch ex As Exception
                Return MASQualityGateResult.Failed(
                    gateKey:="output-application-route",
                    displayName:="Output Product Route Gate",
                    ownerName:="ApplicationSystem / OutputSystem / CertificationSystem",
                    certificationSystemKey:="output-application-route",
                    errorCount:=1,
                    warningCount:=0,
                    summary:="Output product route audit threw before completing the public facade, capability catalog proof, Chart/Report/Render Verification foundation proof, and product evidence bundle proof.",
                    details:=New String() {If(ex.Message, String.Empty)})
            End Try
        End Function


        Private Shared Function RunComponentCoverageGate() As MASQualityGateResult
            Try
                Dim report As MASQualityComponentCoverageReport = MASQualityComponentCoverageMap.BuildCurrent()
                If report Is Nothing OrElse report.HasBlockingCoverageGaps Then
                    Dim gapCount As Integer = 1
                    Dim details As IReadOnlyList(Of String) = New String() {"Component coverage map returned no report."}
                    If report IsNot Nothing Then
                        gapCount = Math.Max(1, report.BlockingGapCount)
                        details = report.CreateBlockingGapDetails(32)
                    End If

                    Return MASQualityGateResult.Failed(
                        gateKey:="component-coverage-map",
                        displayName:="Component Registry Coverage Map",
                        ownerName:="CertificationSystem / ArchitectureSystem / RenderVerificationSystem",
                        certificationSystemKey:="component-coverage-map",
                        errorCount:=gapCount,
                        warningCount:=0,
                        summary:="One or more registered component descriptors have no trusted Quality coverage classification.",
                        details:=details)
                End If

                Return MASQualityGateResult.Passed(
                    gateKey:="component-coverage-map",
                    displayName:="Component Registry Coverage Map",
                    ownerName:="CertificationSystem / ArchitectureSystem / RenderVerificationSystem",
                    certificationSystemKey:="component-coverage-map",
                    summary:=report.Summary,
                    details:=report.CreateSampleDetails(24))
            Catch ex As Exception
                Return MASQualityGateResult.Failed(
                    gateKey:="component-coverage-map",
                    displayName:="Component Registry Coverage Map",
                    ownerName:="CertificationSystem / ArchitectureSystem / RenderVerificationSystem",
                    certificationSystemKey:="component-coverage-map",
                    errorCount:=1,
                    warningCount:=0,
                    summary:="Component coverage map evaluation threw before every descriptor could be classified.",
                    details:=New String() {If(ex.Message, String.Empty)})
            End Try
        End Function


        Private Shared Function RunRenderVerificationCoverageGate() As MASQualityGateResult
            Try
                Dim report As MASRenderVerificationCoverageReport = MASRenderVerificationCoverageAudit.BuildCurrent()
                If report Is Nothing OrElse Not report.IsComplete Then
                    Dim findingCount As Integer = 1
                    Dim details As IReadOnlyList(Of String) = New String() {"Render-verification coverage audit returned no report."}
                    If report IsNot Nothing Then
                        findingCount = Math.Max(1, report.FindingCount)
                        details = report.CreateFindingDetails(32)
                    End If

                    Return MASQualityGateResult.Failed(
                        gateKey:="render-verification-coverage",
                        displayName:="Render Verification Coverage Graph",
                        ownerName:="RenderVerificationSystem / CertificationSystem",
                        certificationSystemKey:="render-verification-coverage",
                        errorCount:=findingCount,
                        warningCount:=0,
                        summary:="Render Verification catalog, capture scenes, and component coverage map are not fully aligned.",
                        details:=details)
                End If

                Return MASQualityGateResult.Passed(
                    gateKey:="render-verification-coverage",
                    displayName:="Render Verification Coverage Graph",
                    ownerName:="RenderVerificationSystem / CertificationSystem",
                    certificationSystemKey:="render-verification-coverage",
                    summary:=report.Summary,
                    details:=report.CreateSummaryDetails())
            Catch ex As Exception
                Return MASQualityGateResult.Failed(
                    gateKey:="render-verification-coverage",
                    displayName:="Render Verification Coverage Graph",
                    ownerName:="RenderVerificationSystem / CertificationSystem",
                    certificationSystemKey:="render-verification-coverage",
                    errorCount:=1,
                    warningCount:=0,
                    summary:="Render Verification coverage graph audit threw before completing the exact catalog comparison.",
                    details:=New String() {If(ex.Message, String.Empty)})
            End Try
        End Function


        Private Shared Function RunRenderVerificationElementCoverageClosureGate() As MASQualityGateResult
            Try
                Dim report As MASRenderVerificationElementCoverageClosureReport = MASRenderVerificationElementCoverageClosureAudit.VerifyCurrent()
                If report Is Nothing OrElse Not report.IsClosed Then
                    Dim errorCount As Integer = If(report Is Nothing, 1, Math.Max(1, report.ErrorCount))
                    Dim details As IReadOnlyList(Of String) = New String() {"Render Verification element coverage closure audit returned no report."}
                    If report IsNot Nothing Then details = report.CreateFindingDetails(32)

                    Return MASQualityGateResult.Failed(
                        gateKey:="render-verification-element-coverage-closure",
                        displayName:="Render Verification Element Coverage Closure Gate",
                        ownerName:="RenderVerificationSystem / CertificationSystem / ArchitectureSystem",
                        certificationSystemKey:="render-verification-element-coverage-closure",
                        errorCount:=errorCount,
                        warningCount:=If(report Is Nothing, 0, report.WarningCount),
                        summary:="Render Verification dashboard element coverage is not fully aligned with the component registry, coverage map, target catalog, and capture-scene registry.",
                        details:=details)
                End If

                If report.WarningCount > 0 Then
                    Return MASQualityGateResult.PassedWithWarnings(
                        gateKey:="render-verification-element-coverage-closure",
                        displayName:="Render Verification Element Coverage Closure Gate",
                        ownerName:="RenderVerificationSystem / CertificationSystem / ArchitectureSystem",
                        certificationSystemKey:="render-verification-element-coverage-closure",
                        warningCount:=report.WarningCount,
                        summary:=report.Summary,
                        details:=report.CreateSummaryDetails())
                End If

                Return MASQualityGateResult.Passed(
                    gateKey:="render-verification-element-coverage-closure",
                    displayName:="Render Verification Element Coverage Closure Gate",
                    ownerName:="RenderVerificationSystem / CertificationSystem / ArchitectureSystem",
                    certificationSystemKey:="render-verification-element-coverage-closure",
                    summary:=report.Summary,
                    details:=report.CreateSummaryDetails())
            Catch ex As Exception
                Return MASQualityGateResult.Failed(
                    gateKey:="render-verification-element-coverage-closure",
                    displayName:="Render Verification Element Coverage Closure Gate",
                    ownerName:="RenderVerificationSystem / CertificationSystem / ArchitectureSystem",
                    certificationSystemKey:="render-verification-element-coverage-closure",
                    errorCount:=1,
                    warningCount:=0,
                    summary:="Render Verification element coverage closure threw before completing the dashboard/read-model proof.",
                    details:=New String() {If(ex.Message, String.Empty)})
            End Try
        End Function


        Private Shared Function RunSizeLayoutElementClosureGate() As MASQualityGateResult
            Try
                Dim report As MASSizeLayoutElementClosureReport = MASSizeLayoutElementClosureAudit.VerifyCurrent()
                If report Is Nothing OrElse Not report.IsClosed Then
                    Dim errorCount As Integer = If(report Is Nothing, 1, Math.Max(1, report.ErrorCount))
                    Dim details As IReadOnlyList(Of String) = New String() {"Size/Layout element closure audit returned no report."}
                    If report IsNot Nothing Then details = report.CreateFindingDetails(32)

                    Return MASQualityGateResult.Failed(
                        gateKey:="size-layout-element-closure",
                        displayName:="Size/Layout Element Closure Gate",
                        ownerName:="SizeLayoutSystem / ArchitectureSystem / CertificationSystem",
                        certificationSystemKey:="size-layout-element-closure",
                        errorCount:=errorCount,
                        warningCount:=If(report Is Nothing, 0, report.WarningCount),
                        summary:="Registered elements are not fully closed against intrinsic size, layout participant, and responsive-consumption ownership.",
                        details:=details)
                End If

                If report.WarningCount > 0 Then
                    Return MASQualityGateResult.PassedWithWarnings(
                        gateKey:="size-layout-element-closure",
                        displayName:="Size/Layout Element Closure Gate",
                        ownerName:="SizeLayoutSystem / ArchitectureSystem / CertificationSystem",
                        certificationSystemKey:="size-layout-element-closure",
                        warningCount:=report.WarningCount,
                        summary:=report.Summary,
                        details:=report.CreateSummaryDetails())
                End If

                Return MASQualityGateResult.Passed(
                    gateKey:="size-layout-element-closure",
                    displayName:="Size/Layout Element Closure Gate",
                    ownerName:="SizeLayoutSystem / ArchitectureSystem / CertificationSystem",
                    certificationSystemKey:="size-layout-element-closure",
                    summary:=report.Summary,
                    details:=report.CreateSummaryDetails())
            Catch ex As Exception
                Return MASQualityGateResult.Failed(
                    gateKey:="size-layout-element-closure",
                    displayName:="Size/Layout Element Closure Gate",
                    ownerName:="SizeLayoutSystem / ArchitectureSystem / CertificationSystem",
                    certificationSystemKey:="size-layout-element-closure",
                    errorCount:=1,
                    warningCount:=0,
                    summary:="Size/Layout element closure threw before completing the registry/intrinsic/responsive proof.",
                    details:=New String() {If(ex.Message, String.Empty)})
            End Try
        End Function

        Private Shared Function RunRenderHitBoundsClosureGate() As MASQualityGateResult
            Try
                Dim report As MASRenderHitBoundsClosureReport = MASRenderHitBoundsClosureAudit.VerifyCurrent()
                If report Is Nothing OrElse Not report.IsClosed Then
                    Dim errorCount As Integer = If(report Is Nothing, 1, Math.Max(1, report.ErrorCount))
                    Dim details As IReadOnlyList(Of String) = New String() {"Render/hit-bounds closure audit returned no report."}
                    If report IsNot Nothing Then details = report.CreateFindingDetails(32)

                    Return MASQualityGateResult.Failed(
                        gateKey:="render-hit-bounds-closure",
                        displayName:="Render / Hit Bounds Closure Gate",
                        ownerName:="SizeLayoutSystem / CoreControls / CertificationSystem",
                        certificationSystemKey:="render-hit-bounds-closure",
                        errorCount:=errorCount,
                        warningCount:=If(report Is Nothing, 0, report.WarningCount),
                        summary:="Render-time bounds, slot semantic rectangles, clip routing, or hit-test bounds are not fully closed against MASLayoutSlot ownership.",
                        details:=details)
                End If

                If report.WarningCount > 0 Then
                    Return MASQualityGateResult.PassedWithWarnings(
                        gateKey:="render-hit-bounds-closure",
                        displayName:="Render / Hit Bounds Closure Gate",
                        ownerName:="SizeLayoutSystem / CoreControls / CertificationSystem",
                        certificationSystemKey:="render-hit-bounds-closure",
                        warningCount:=report.WarningCount,
                        summary:=report.Summary,
                        details:=report.CreateSummaryDetails())
                End If

                Return MASQualityGateResult.Passed(
                    gateKey:="render-hit-bounds-closure",
                    displayName:="Render / Hit Bounds Closure Gate",
                    ownerName:="SizeLayoutSystem / CoreControls / CertificationSystem",
                    certificationSystemKey:="render-hit-bounds-closure",
                    summary:=report.Summary,
                    details:=report.CreateSummaryDetails())
            Catch ex As Exception
                Return MASQualityGateResult.Failed(
                    gateKey:="render-hit-bounds-closure",
                    displayName:="Render / Hit Bounds Closure Gate",
                    ownerName:="SizeLayoutSystem / CoreControls / CertificationSystem",
                    certificationSystemKey:="render-hit-bounds-closure",
                    errorCount:=1,
                    warningCount:=0,
                    summary:="Render/hit-bounds closure threw before completing the slot/render/hit proof.",
                    details:=New String() {If(ex.Message, String.Empty)})
            End Try
        End Function

        Private Shared Function RunDeadPathClosureGate(projectRoot As String) As MASQualityGateResult
            Dim root As String = ResolveProjectRoot(projectRoot)
            If String.IsNullOrWhiteSpace(root) Then
                Return MASQualityGateResult.Skipped(
                    gateKey:="dead-path-closure",
                    displayName:="Dead Path / Parallel Path Closure Gate",
                    ownerName:="CertificationSystem / SourceTree",
                    certificationSystemKey:="dead-path-closure",
                    summary:="The repository root was not available in the current runtime context, so final dead-path closure remains delegated to tools/quality.",
                    details:=New String() {"Run tools/quality/Run-NexamasUIQuality.ps1 -StaticOnly from the repository root for a blocking source-tree proof."})
            End If

            Try
                Dim report As MASDeadPathClosureReport = MASDeadPathClosureAudit.Evaluate(root)
                If report Is Nothing OrElse Not report.IsClosed Then
                    Dim errorCount As Integer = If(report Is Nothing, 1, Math.Max(1, report.ErrorCount))
                    Dim warningCount As Integer = If(report Is Nothing, 0, report.WarningCount)
                    Dim details As IReadOnlyList(Of String) = New String() {"Dead-path closure audit returned no report."}
                    If report IsNot Nothing Then details = report.CreateFindingDetails(40)

                    Return MASQualityGateResult.Failed(
                        gateKey:="dead-path-closure",
                        displayName:="Dead Path / Parallel Path Closure Gate",
                        ownerName:="CertificationSystem / SourceTree",
                        certificationSystemKey:="dead-path-closure",
                        errorCount:=errorCount,
                        warningCount:=warningCount,
                        summary:="The source tree still contains missing declared assets, duplicate Includes, unowned active source, or root-level generated-output paths.",
                        details:=details)
                End If

                If report.WarningCount > 0 Then
                    Return MASQualityGateResult.PassedWithWarnings(
                        gateKey:="dead-path-closure",
                        displayName:="Dead Path / Parallel Path Closure Gate",
                        ownerName:="CertificationSystem / SourceTree",
                        certificationSystemKey:="dead-path-closure",
                        warningCount:=report.WarningCount,
                        summary:=report.Summary,
                        details:=report.CreateSummaryDetails())
                End If

                Return MASQualityGateResult.Passed(
                    gateKey:="dead-path-closure",
                    displayName:="Dead Path / Parallel Path Closure Gate",
                    ownerName:="CertificationSystem / SourceTree",
                    certificationSystemKey:="dead-path-closure",
                    summary:=report.Summary,
                    details:=report.CreateSummaryDetails())
            Catch ex As Exception
                Return MASQualityGateResult.Failed(
                    gateKey:="dead-path-closure",
                    displayName:="Dead Path / Parallel Path Closure Gate",
                    ownerName:="CertificationSystem / SourceTree",
                    certificationSystemKey:="dead-path-closure",
                    errorCount:=1,
                    warningCount:=0,
                    summary:="Dead-path closure audit threw before completing the source-tree proof.",
                    details:=New String() {If(ex.Message, String.Empty)})
            End Try
        End Function


        Private Shared Function RunSizeLayoutRuntimeVerificationGate() As MASQualityGateResult
            Try
                Dim report As MASSizeLayoutRuntimeVerificationReport = MASSizeLayoutRuntimeVerificationAudit.VerifyCurrent()
                If report Is Nothing OrElse Not report.IsVerified Then
                    Dim errorCount As Integer = If(report Is Nothing, 1, Math.Max(1, report.ErrorCount))
                    Dim details As IReadOnlyList(Of String) = New String() {"Size/Layout runtime verification audit returned no report."}
                    If report IsNot Nothing Then details = report.CreateFindingDetails(32)

                    Return MASQualityGateResult.Failed(
                        gateKey:="size-layout-runtime-verification",
                        displayName:="Size/Layout Runtime Verification Gate",
                        ownerName:="SizeLayoutSystem / CertificationSystem",
                        certificationSystemKey:="size-layout-runtime-verification",
                        errorCount:=errorCount,
                        warningCount:=If(report Is Nothing, 0, report.WarningCount),
                        summary:="Size/Layout runtime resolver, profile, DPI, tiny-bounds, hit/visual overflow, or governance probes are not fully verified.",
                        details:=details)
                End If

                If report.WarningCount > 0 Then
                    Return MASQualityGateResult.PassedWithWarnings(
                        gateKey:="size-layout-runtime-verification",
                        displayName:="Size/Layout Runtime Verification Gate",
                        ownerName:="SizeLayoutSystem / CertificationSystem",
                        certificationSystemKey:="size-layout-runtime-verification",
                        warningCount:=report.WarningCount,
                        summary:=report.Summary,
                        details:=report.CreateSummaryDetails())
                End If

                Return MASQualityGateResult.Passed(
                    gateKey:="size-layout-runtime-verification",
                    displayName:="Size/Layout Runtime Verification Gate",
                    ownerName:="SizeLayoutSystem / CertificationSystem",
                    certificationSystemKey:="size-layout-runtime-verification",
                    summary:=report.Summary,
                    details:=report.CreateSummaryDetails())
            Catch ex As Exception
                Return MASQualityGateResult.Failed(
                    gateKey:="size-layout-runtime-verification",
                    displayName:="Size/Layout Runtime Verification Gate",
                    ownerName:="SizeLayoutSystem / CertificationSystem",
                    certificationSystemKey:="size-layout-runtime-verification",
                    errorCount:=1,
                    warningCount:=0,
                    summary:="Size/Layout runtime verification threw before completing the resolver/profile/bounds proof.",
                    details:=New String() {If(ex.Message, String.Empty)})
            End Try
        End Function


        Private Shared Function RunPerformanceDiagnosticsOrchestrationGate() As MASQualityGateResult
            Try
                Dim report As MASPerformanceDiagnosticsOrchestrationReport = MASPerformanceDiagnosticsOrchestrationAudit.VerifyCurrent()
                If report Is Nothing OrElse Not report.IsVerified Then
                    Dim errorCount As Integer = If(report Is Nothing, 1, Math.Max(1, report.ErrorCount))
                    Dim details As IReadOnlyList(Of String) = New String() {"Performance/Diagnostics orchestration audit returned no report."}
                    If report IsNot Nothing Then details = report.CreateFindingDetails(32)

                    Return MASQualityGateResult.Failed(
                        gateKey:="performance-diagnostics-orchestration",
                        displayName:="Performance/Diagnostics Orchestration Gate",
                        ownerName:="PerformanceSystem / DiagnosticsDashboardSystem / CertificationSystem",
                        certificationSystemKey:="performance-diagnostics-orchestration",
                        errorCount:=errorCount,
                        warningCount:=If(report Is Nothing, 0, report.WarningCount),
                        summary:="PerformanceSystem counters, Diagnostics Dashboard availability facts, virtualization bridge, or release-certification chain are not fully verified.",
                        details:=details)
                End If

                If report.WarningCount > 0 Then
                    Return MASQualityGateResult.PassedWithWarnings(
                        gateKey:="performance-diagnostics-orchestration",
                        displayName:="Performance/Diagnostics Orchestration Gate",
                        ownerName:="PerformanceSystem / DiagnosticsDashboardSystem / CertificationSystem",
                        certificationSystemKey:="performance-diagnostics-orchestration",
                        warningCount:=report.WarningCount,
                        summary:=report.Summary,
                        details:=report.CreateSummaryDetails())
                End If

                Return MASQualityGateResult.Passed(
                    gateKey:="performance-diagnostics-orchestration",
                    displayName:="Performance/Diagnostics Orchestration Gate",
                    ownerName:="PerformanceSystem / DiagnosticsDashboardSystem / CertificationSystem",
                    certificationSystemKey:="performance-diagnostics-orchestration",
                    summary:=report.Summary,
                    details:=report.CreateSummaryDetails())
            Catch ex As Exception
                Return MASQualityGateResult.Failed(
                    gateKey:="performance-diagnostics-orchestration",
                    displayName:="Performance/Diagnostics Orchestration Gate",
                    ownerName:="PerformanceSystem / DiagnosticsDashboardSystem / CertificationSystem",
                    certificationSystemKey:="performance-diagnostics-orchestration",
                    errorCount:=1,
                    warningCount:=0,
                    summary:="Performance/Diagnostics orchestration threw before completing the snapshot/dashboard/certification proof.",
                    details:=New String() {If(ex.Message, String.Empty)})
            End Try
        End Function


        Private Shared Function RunRenderVerificationReadinessGate() As MASQualityGateResult
            Try
                Dim targets As IReadOnlyList(Of MASRenderVerificationTarget) = MASRenderVerificationTargetCatalog.CreateAllTargets()
                Dim store As New MASRenderBaselineStore(Path.Combine(Path.GetTempPath(), "Nexamas UI", "QualityOrchestrator", "RenderVerification"))
                Dim report As MASRenderVerificationReport = MASRenderVerificationGate.Evaluate(targets, store)
                Dim details As New List(Of String)()

                If report IsNot Nothing AndAlso report.Findings IsNot Nothing Then
                    For Each finding As MASRenderVerificationFinding In report.Findings
                        If finding IsNot Nothing AndAlso details.Count < 24 Then details.Add(finding.ToString())
                    Next
                End If

                If report Is Nothing OrElse Not report.IsReady Then
                    Dim errorCount As Integer = If(report Is Nothing, 1, Math.Max(1, report.ErrorCount))
                    Return MASQualityGateResult.Failed(
                        gateKey:="render-verification-readiness",
                        displayName:="Render Verification Readiness Gate",
                        ownerName:="RenderVerificationSystem",
                        certificationSystemKey:="render-verification",
                        errorCount:=errorCount,
                        warningCount:=0,
                        summary:="Render Verification target catalog is not ready for deterministic capture.",
                        details:=details)
                End If

                Return MASQualityGateResult.Passed(
                    gateKey:="render-verification-readiness",
                    displayName:="Render Verification Readiness Gate",
                    ownerName:="RenderVerificationSystem",
                    certificationSystemKey:="render-verification",
                    summary:=report.TargetCount.ToString(CultureInfo.InvariantCulture) & " target(s) and " & report.ScenarioCount.ToString(CultureInfo.InvariantCulture) & " scenario(s) passed readiness validation.",
                    details:=New String() {"No render-verification readiness errors were found."})
            Catch ex As Exception
                Return MASQualityGateResult.Failed(
                    gateKey:="render-verification-readiness",
                    displayName:="Render Verification Readiness Gate",
                    ownerName:="RenderVerificationSystem",
                    certificationSystemKey:="render-verification",
                    errorCount:=1,
                    warningCount:=0,
                    summary:="Render Verification readiness evaluation threw before completing the catalog proof.",
                    details:=New String() {If(ex.Message, String.Empty)})
            End Try
        End Function

        Private Shared Function RunSurfaceMaterialProofGate() As MASQualityGateResult
            Try
                Dim report As MASRenderVerificationSurfaceMaterialProofReport = MASRenderVerificationSurfaceMaterialProofAudit.BuildCurrent()
                If report Is Nothing OrElse Not report.IsComplete Then
                    Dim details As New List(Of String)()
                    If report IsNot Nothing Then
                        details.Add("Status: " & report.Status.ToString())
                        details.Add("Runtime consumer proof count: " & report.CompleteProofCount.ToString(CultureInfo.InvariantCulture) & " / " & report.ExpectedRuntimeSurfaceVisualConsumerCount.ToString(CultureInfo.InvariantCulture))
                        details.Add("Public gateway proof count: " & report.ProofedPublicGatewayMemberCount.ToString(CultureInfo.InvariantCulture) & " / " & report.ExpectedPublicGatewayMemberCount.ToString(CultureInfo.InvariantCulture))
                        If report.MissingRuntimeConsumerProofCount > 0 Then details.Add("Missing runtime consumer proof count: " & report.MissingRuntimeConsumerProofCount.ToString(CultureInfo.InvariantCulture))
                        If report.MissingPublicGatewayProofCount > 0 Then details.Add("Missing public gateway proof count: " & report.MissingPublicGatewayProofCount.ToString(CultureInfo.InvariantCulture))
                    End If

                    Return MASQualityGateResult.Failed(
                        gateKey:="surface-material-proof",
                        displayName:="Surface Material Render Proof Gate",
                        ownerName:="RenderVerificationSystem",
                        certificationSystemKey:="showcase-surface-materials",
                        errorCount:=1,
                        warningCount:=0,
                        summary:="Surface material runtime/public gateway proof is incomplete.",
                        details:=details)
                End If

                Return MASQualityGateResult.Passed(
                    gateKey:="surface-material-proof",
                    displayName:="Surface Material Render Proof Gate",
                    ownerName:="RenderVerificationSystem",
                    certificationSystemKey:="showcase-surface-materials",
                    summary:=report.EntryCount.ToString(CultureInfo.InvariantCulture) & " runtime surface material consumer(s) have catalog scenarios, registered capture scenes, and public gateway route proof.",
                    details:=New String() {report.Notes})
            Catch ex As Exception
                Return MASQualityGateResult.Failed(
                    gateKey:="surface-material-proof",
                    displayName:="Surface Material Render Proof Gate",
                    ownerName:="RenderVerificationSystem",
                    certificationSystemKey:="showcase-surface-materials",
                    errorCount:=1,
                    warningCount:=0,
                    summary:="Surface material proof audit threw before completing the route proof.",
                    details:=New String() {If(ex.Message, String.Empty)})
            End Try
        End Function

        Private Shared Function RunCertificationOrchestrationClosureGate(results As IEnumerable(Of MASQualityGateResult)) As MASQualityGateResult
            Try
                Dim report As MASCertificationOrchestrationClosureReport = MASCertificationOrchestrationClosureAudit.Verify(results)
                If report Is Nothing OrElse Not report.IsClosed Then
                    Dim findingCount As Integer = If(report Is Nothing, 1, Math.Max(1, report.FindingCount))
                    Dim details As IReadOnlyList(Of String) = New String() {"Certification orchestration closure audit returned no report."}
                    If report IsNot Nothing Then details = report.CreateFindingDetails(32)

                    Return MASQualityGateResult.Failed(
                        gateKey:="certification-orchestration-closure",
                        displayName:="Certification Orchestration Closure Gate",
                        ownerName:="CertificationSystem / QualityOrchestrator",
                        certificationSystemKey:="certification-orchestration-closure",
                        errorCount:=findingCount,
                        warningCount:=0,
                        summary:="Certification Manifest is not fully closed against the Quality Orchestrator gate graph.",
                        details:=details)
                End If

                Return MASQualityGateResult.Passed(
                    gateKey:="certification-orchestration-closure",
                    displayName:="Certification Orchestration Closure Gate",
                    ownerName:="CertificationSystem / QualityOrchestrator",
                    certificationSystemKey:="certification-orchestration-closure",
                    summary:=report.Summary,
                    details:=report.CreateSummaryDetails())
            Catch ex As Exception
                Return MASQualityGateResult.Failed(
                    gateKey:="certification-orchestration-closure",
                    displayName:="Certification Orchestration Closure Gate",
                    ownerName:="CertificationSystem / QualityOrchestrator",
                    certificationSystemKey:="certification-orchestration-closure",
                    errorCount:=1,
                    warningCount:=0,
                    summary:="Certification orchestration closure threw before completing the manifest/gate ownership proof.",
                    details:=New String() {If(ex.Message, String.Empty)})
            End Try
        End Function


        Private Shared Function ResolveProjectRoot(projectRoot As String) As String
            If Not String.IsNullOrWhiteSpace(projectRoot) Then
                Dim explicitRoot As String = Path.GetFullPath(projectRoot.Trim())
                If Directory.Exists(explicitRoot) AndAlso File.Exists(Path.Combine(explicitRoot, "Nexamas.UI.vbproj")) Then Return explicitRoot
            End If

            Dim candidates As New List(Of String)()
            Try
                candidates.Add(Environment.CurrentDirectory)
            Catch masCaughtExceptionCurrentDirectory As Exception
                Nexamas.UI.Diagnostics.MASExceptionSilencer.SwallowDiagnosticOnly(
                    masCaughtExceptionCurrentDirectory,
                    "MASQualityOrchestrator.ResolveProjectRoot.CurrentDirectory")
            End Try

            Try
                candidates.Add(AppDomain.CurrentDomain.BaseDirectory)
            Catch masCaughtExceptionBaseDirectory As Exception
                Nexamas.UI.Diagnostics.MASExceptionSilencer.SwallowDiagnosticOnly(
                    masCaughtExceptionBaseDirectory,
                    "MASQualityOrchestrator.ResolveProjectRoot.BaseDirectory")
            End Try

            For Each candidate As String In candidates
                Dim resolved As String = WalkForProjectRoot(candidate)
                If Not String.IsNullOrWhiteSpace(resolved) Then Return resolved
            Next

            Return String.Empty
        End Function

        Private Shared Function WalkForProjectRoot(startDirectory As String) As String
            If String.IsNullOrWhiteSpace(startDirectory) Then Return String.Empty

            Dim current As DirectoryInfo = Nothing
            Try
                current = New DirectoryInfo(Path.GetFullPath(startDirectory.Trim()))
            Catch masCaughtExceptionRootWalk As Exception
                Nexamas.UI.Diagnostics.MASExceptionSilencer.SwallowDiagnosticOnly(
                    masCaughtExceptionRootWalk,
                    "MASQualityOrchestrator.WalkForProjectRoot.StartDirectory")
                Return String.Empty
            End Try

            Dim depth As Integer = 0
            While current IsNot Nothing AndAlso depth < 10
                If File.Exists(Path.Combine(current.FullName, "Nexamas.UI.vbproj")) Then Return current.FullName
                current = current.Parent
                depth += 1
            End While

            Return String.Empty
        End Function
    End Class

End Namespace
