using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Threading;

namespace EonaCat.LogStack.Telemetry;

/// <summary>
/// Advanced telemetry engine with adaptive sampling, anomaly detection and self-tuning.
/// Designed as an extension layer beyond standard telemetry pipelines.
/// </summary>
public sealed class AdaptiveTelemetryEngine
{
    private readonly ConcurrentDictionary<string, TelemetrySignal> _signals = new();
    private long _events;

    public int MaxSignalHistory { get; set; } = 1024;
    public bool AdaptiveSampling { get; set; } = true;
    public bool DetectAnomalies { get; set; } = true;

    public void Record(string name, double value, params (string Key, string Value)[] tags)
    {
        var signal = _signals.GetOrAdd(name, _ => new TelemetrySignal(name));
        signal.Record(value, tags, MaxSignalHistory);
        Interlocked.Increment(ref _events);

        if (DetectAnomalies)
            signal.UpdateAnomalyState();
    }

    public TelemetryEngineSnapshot Snapshot()
    {
        var snapshot = new TelemetryEngineSnapshot { TotalEvents = Interlocked.Read(ref _events) };
        foreach (var item in _signals)
            snapshot.Signals[item.Key] = item.Value.Snapshot();
        return snapshot;
    }
}
