﻿Option Strict On
Option Explicit On

Imports System
Imports System.IO
Imports System.Text

''' <summary>
''' Records fatal Showcase boundary failures outside the Nexamas.UI visual tree.
''' This is host diagnostics only; it does not imitate a Nexamas.UI service.
''' </summary>
Friend NotInheritable Class ShowcaseRuntimeFaultReporter

    Private Sub New()
    End Sub

    Friend Shared Sub ReportFatal(context As String, ex As Exception)
        Dim report As String = BuildReport(context, ex)
        Dim reportPath As String = TryWriteReport(report)
        Dim deepest As Exception = ResolveDeepestException(ex)
        Dim detail As String = If(deepest Is Nothing, "Unknown runtime failure.", deepest.GetType().FullName & ": " & deepest.Message)

        Dim message As String = If(context, "The Nexamas UI Showcase stopped because of an unexpected runtime failure.") &
                                Environment.NewLine & Environment.NewLine &
                                detail
        If Not String.IsNullOrWhiteSpace(reportPath) Then
            message &= Environment.NewLine & Environment.NewLine & "Full report:" & Environment.NewLine & reportPath
        End If

        Dim automatedSmoke As Boolean = String.Equals(
            Environment.GetEnvironmentVariable("NEXAMAS_SHOWCASE_RUNTIME_SMOKE"),
            "1",
            StringComparison.OrdinalIgnoreCase)

        If automatedSmoke Then
            Environment.ExitCode = 1
            System.Diagnostics.Debug.WriteLine(report)
            Return
        End If

        Try
            If NexamasUIShowcaseWindowBase.TryReportUnhandledNexamasUIError(message, ex) Then
                Return
            End If
        Catch dialogException As Exception
            System.Diagnostics.Debug.WriteLine("Nexamas UI Showcase fatal dialog boundary: " & dialogException.Message)
        End Try

        ' When no live Showcase window exists, the durable LocalAppData report
        ' and debugger output are the only safe host-level fallbacks. Do not
        ' create a native WinForms MessageBox parallel to Nexamas.UI surfaces.
        System.Diagnostics.Debug.WriteLine(report)
    End Sub

    Friend Shared Function BuildReport(context As String, ex As Exception) As String
        Dim builder As New StringBuilder()
        builder.AppendLine("Nexamas UI Showcase runtime failure")
        builder.AppendLine("UTC: " & DateTime.UtcNow.ToString("O", Globalization.CultureInfo.InvariantCulture))
        builder.AppendLine("Context: " & If(context, String.Empty))
        builder.AppendLine("Executable: " & System.Windows.Forms.Application.ExecutablePath)
        builder.AppendLine("OS: " & Environment.OSVersion.ToString())
        builder.AppendLine("CLR: " & Environment.Version.ToString())
        builder.AppendLine("64-bit process: " & Environment.Is64BitProcess.ToString())
        builder.AppendLine()

        Dim current As Exception = ex
        Dim depth As Integer = 0
        While current IsNot Nothing
            builder.AppendLine("Exception[" & depth.ToString(Globalization.CultureInfo.InvariantCulture) & "]: " & current.GetType().FullName)
            builder.AppendLine("Message: " & current.Message)
            builder.AppendLine(current.StackTrace)
            builder.AppendLine()
            current = current.InnerException
            depth += 1
        End While

        Return builder.ToString()
    End Function

    Private Shared Function TryWriteReport(report As String) As String
        Try
            Dim rootDirectory As String = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Nexamas", "Showcase")
            System.IO.Directory.CreateDirectory(rootDirectory)
            Dim reportPath As String = System.IO.Path.Combine(rootDirectory, "Nexamas.UI.Showcase.runtime-error.log")
            System.IO.File.WriteAllText(reportPath, If(report, String.Empty), New UTF8Encoding(encoderShouldEmitUTF8Identifier:=False))
            Return reportPath
        Catch writeException As Exception
            System.Diagnostics.Debug.WriteLine("Showcase runtime report write failed: " & writeException.Message)
            Return String.Empty
        End Try
    End Function

    Private Shared Function ResolveDeepestException(ex As Exception) As Exception
        Dim current As Exception = ex
        While current IsNot Nothing AndAlso current.InnerException IsNot Nothing
            current = current.InnerException
        End While
        Return current
    End Function
End Class
