using System.Diagnostics;
using System.Diagnostics.Metrics;
using StellaOps.Scanner.Core.Contracts;
using StellaOps.Scanner.Core.Utility;

namespace StellaOps.Scanner.Core.Observability;

public static class ScannerDiagnostics
{
    public const string ActivitySourceName = "StellaOps.Scanner";
    public const string ActivityVersion = "1.0.0";
    public const string MeterName = "stellaops.scanner";
    public const string MeterVersion = "1.0.0";

    public static ActivitySource ActivitySource { get; } = new(ActivitySourceName, ActivityVersion);
    public static Meter Meter { get; } = new(MeterName, MeterVersion);

    public static Activity? StartActivity(
        string name,
        ScanJobId jobId,
        string? stage = null,
        string? component = null,
        ActivityKind kind = ActivityKind.Internal,
        IEnumerable<KeyValuePair<string, object?>>? tags = null)
    {
        var activity = ActivitySource.StartActivity(name, kind);
        if (activity is null)
        {
            return null;
        }

        activity.SetTag("stellaops.scanner.job_id", jobId.ToString());
        activity.SetTag("stellaops.scanner.correlation_id", ScannerIdentifiers.CreateCorrelationId(jobId, stage, component));

        if (!string.IsNullOrWhiteSpace(stage))
        {
            activity.SetTag("stellaops.scanner.stage", stage);
        }

        if (!string.IsNullOrWhiteSpace(component))
        {
            activity.SetTag("stellaops.scanner.component", component);
        }

        if (tags is not null)
        {
            foreach (var tag in tags)
            {
                activity?.SetTag(tag.Key, tag.Value);
            }
        }

        return activity;
    }
}
