using System;
using System.Diagnostics;

namespace EonaCat.LogStack.Telemetry;

/// <summary>
/// Lightweight tracing API compatible with common tracing workflows.
/// </summary>
public sealed class TelemetryActivitySource
{
    public TelemetrySpan StartActivity(string name, string kind = "internal")
    {
        return new TelemetrySpan
        {
            Name = name,
            Kind = kind
        };
    }

    public IDisposable StartScope(string name, Action<TelemetrySpan>? completed = null)
    {
        var span = StartActivity(name);
        var start = Stopwatch.GetTimestamp();

        return new Scope(() =>
        {
            var elapsedTicks = Stopwatch.GetTimestamp() - start;
            span.DurationMs = elapsedTicks * 1000.0 / Stopwatch.Frequency;
            span.Status = "Ok";
            completed?.Invoke(span);
        });
    }

    private sealed class Scope : IDisposable
    {
        private readonly Action _dispose;
        public Scope(Action dispose) => _dispose = dispose;
        public void Dispose() => _dispose();
    }
}
