using Serilog.Events;

namespace Predictalytics.WinFormsHost;

/// <summary>
/// Creates a thread-safe write action for the RichTextBox terminal.
/// </summary>
public static class TerminalHelper
{
    public static Action<string, LogEventLevel> CreateWriteAction(RichTextBox rtb, Control owner)
    {
        int lineCount = 0;
        const int maxLines = 500;

        return (message, level) =>
        {
            if (owner.IsDisposed || rtb.IsDisposed) return;

            try
            {
                owner.BeginInvoke(() =>
                {
                    if (rtb.IsDisposed) return;

                    lineCount++;
                    if (lineCount > maxLines)
                    {
                        rtb.Clear();
                        lineCount = 0;
                        rtb.AppendText("[Terminal cleared — log continues]\n");
                    }

                    var color = level switch
                    {
                        LogEventLevel.Error or LogEventLevel.Fatal => System.Drawing.Color.FromArgb(255, 82, 82),
                        LogEventLevel.Warning => System.Drawing.Color.FromArgb(255, 193, 7),
                        LogEventLevel.Debug => System.Drawing.Color.FromArgb(158, 158, 158),
                        _ => System.Drawing.Color.FromArgb(76, 175, 80)
                    };

                    rtb.SelectionStart = rtb.TextLength;
                    rtb.SelectionLength = 0;
                    rtb.SelectionColor = color;
                    rtb.AppendText(message);
                    rtb.SelectionColor = rtb.ForeColor;
                    rtb.ScrollToCaret();
                });
            }
            catch { /* UI thread shutting down */ }
        };
    }
}
