using System.Diagnostics;

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

/// <summary>
///     PR 6.1 — In-box <see cref="ActivitySource"/> wired around every gw call the
///     driver makes (Subscribe/Unsubscribe, Write/WriteSecured, GetHierarchy). The
///     decorators in this folder produce one span per call, tagged with the inputs
///     ops needs to triage a slow or failing operation:
///     <c>galaxy.tag_count</c>, <c>galaxy.success_count</c>, <c>galaxy.client</c>.
///     <para>
///     The driver itself doesn't take a dependency on the OpenTelemetry packages —
///     <c>System.Diagnostics.ActivitySource</c> is in the BCL. The host process
///     decides which listener (OTLP exporter, Application Insights, dotnet-trace)
///     subscribes to <see cref="ActivitySourceName"/>.
///     </para>
/// </summary>
internal static class GalaxyTelemetry
{
    public const string ActivitySourceName = "ZB.MOM.WW.OtOpcUa.Driver.Galaxy";

    public static readonly ActivitySource ActivitySource = new(ActivitySourceName);

    /// <summary>
    ///     Tag a span with a failure reason and set its status to <c>Error</c>. Helper
    ///     so the decorators don't repeat the four-line idiom on every catch block.
    /// </summary>
    /// <param name="activity">The activity to tag with error information.</param>
    /// <param name="ex">The exception to record.</param>
    public static void RecordError(this Activity? activity, Exception ex)
    {
        if (activity is null) return;
        activity.SetStatus(ActivityStatusCode.Error, ex.Message);
        activity.SetTag("exception.type", ex.GetType().FullName);
        activity.SetTag("exception.message", ex.Message);
    }
}
