using System.Windows.Threading;
using NexusShell.Services.Diagnostics;

namespace NexusShell.Services;

public sealed class UiLatencyMonitor
{
    private readonly PerformanceMonitorService _performance;
    private readonly Dispatcher _dispatcher;
    private readonly DispatcherTimer _probeTimer;
    private readonly NexusTimerRegistration _timerRegistration;
    private long _lastProbeUtc;

    public UiLatencyMonitor(PerformanceMonitorService performance, Dispatcher dispatcher)
    {
        _performance = performance;
        _dispatcher = dispatcher;
        var interval = NexusMotionPreferences.PerformanceModeEnabled()
            ? TimeSpan.FromSeconds(5)
            : TimeSpan.FromSeconds(2);
        _probeTimer = new DispatcherTimer(DispatcherPriority.Background, dispatcher)
        {
            Interval = interval,
        };
        _probeTimer.Tick += (_, _) => ProbeUiThread();
        _timerRegistration = NexusTimerRegistry.Register(
            "ui-latency-probe",
            nameof(UiLatencyMonitor),
            interval,
            uiThread: true,
            "Dispatcher delay probe");
        _lastProbeUtc = DateTime.UtcNow.Ticks;
    }

    public void Start() => _probeTimer.Start();

    public void Stop()
    {
        _probeTimer.Stop();
        _timerRegistration.Dispose();
    }

    private void ProbeUiThread()
    {
        var scheduledAt = DateTime.UtcNow.Ticks;
        _ = _dispatcher.InvokeAsync(() =>
        {
            var latencyMs = (DateTime.UtcNow.Ticks - scheduledAt) / TimeSpan.TicksPerMillisecond;
            _performance.RecordUiLatency(latencyMs);
        }, DispatcherPriority.Normal);
    }
}
