using ZB.MOM.WW.MxGateway.Contracts.Proto.Galaxy;
using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Runtime;

namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Browse;

/// <summary>
///     PR 6.1 — Decorator that emits one <see cref="System.Diagnostics.Activity"/> span
///     per <c>GetHierarchy</c> RPC. <c>galaxy.object_count</c> on the span lets ops
///     correlate slow Discover passes with Galaxy size without instrumenting the
///     discoverer's translation step.
/// </summary>
internal sealed class TracedGalaxyHierarchySource(IGalaxyHierarchySource inner, string clientName) : IGalaxyHierarchySource
{
    /// <inheritdoc />
    public async Task<IReadOnlyList<GalaxyObject>> GetHierarchyAsync(CancellationToken cancellationToken)
    {
        using var activity = GalaxyTelemetry.ActivitySource.StartActivity("galaxy.get_hierarchy");
        activity?.SetTag("galaxy.client", clientName);
        try
        {
            var hierarchy = await inner.GetHierarchyAsync(cancellationToken).ConfigureAwait(false);
            activity?.SetTag("galaxy.object_count", hierarchy.Count);
            return hierarchy;
        }
        catch (Exception ex)
        {
            activity.RecordError(ex);
            throw;
        }
    }
}
