using System;
using System.Diagnostics.Metrics;

namespace StellaOps.Feedser.Source.Vndr.Apple.Internal;

public sealed class AppleDiagnostics : IDisposable
{
    public const string MeterName = "StellaOps.Feedser.Source.Vndr.Apple";
    private const string MeterVersion = "1.0.0";

    private readonly Meter _meter;
    private readonly Counter<long> _fetchItems;
    private readonly Counter<long> _fetchFailures;
    private readonly Counter<long> _fetchUnchanged;
    private readonly Counter<long> _parseFailures;
    private readonly Histogram<long> _mapAffected;

    public AppleDiagnostics()
    {
        _meter = new Meter(MeterName, MeterVersion);
        _fetchItems = _meter.CreateCounter<long>(
            name: "apple.fetch.items",
            unit: "documents",
            description: "Number of Apple advisories fetched.");
        _fetchFailures = _meter.CreateCounter<long>(
            name: "apple.fetch.failures",
            unit: "operations",
            description: "Number of Apple fetch failures.");
        _fetchUnchanged = _meter.CreateCounter<long>(
            name: "apple.fetch.unchanged",
            unit: "documents",
            description: "Number of Apple advisories skipped due to 304 responses.");
        _parseFailures = _meter.CreateCounter<long>(
            name: "apple.parse.failures",
            unit: "documents",
            description: "Number of Apple documents that failed to parse.");
        _mapAffected = _meter.CreateHistogram<long>(
            name: "apple.map.affected.count",
            unit: "packages",
            description: "Distribution of affected package counts emitted per Apple advisory.");
    }

    public Meter Meter => _meter;

    public void FetchItem() => _fetchItems.Add(1);

    public void FetchFailure() => _fetchFailures.Add(1);

    public void FetchUnchanged() => _fetchUnchanged.Add(1);

    public void ParseFailure() => _parseFailures.Add(1);

    public void MapAffectedCount(int count)
    {
        if (count >= 0)
        {
            _mapAffected.Record(count);
        }
    }

    public void Dispose() => _meter.Dispose();
}
