using System.Collections.Concurrent;

namespace LightlessSync.PlayerData.Pairs;

public readonly record struct PairPerformanceMetrics(
    long TriangleCount,
    long ApproximateVramBytes,
    long ApproximateEffectiveVramBytes);

/// <summary>
///     caches performance metrics keyed by pair ident
/// </summary>
public sealed class PairPerformanceMetricsCache
{
    private sealed record CacheEntry(string DataHash, PairPerformanceMetrics Metrics);

    private readonly ConcurrentDictionary<string, CacheEntry> _cache = new(StringComparer.Ordinal);

    public bool TryGetMetrics(string ident, string dataHash, out PairPerformanceMetrics metrics)
    {
        metrics = default;
        if (string.IsNullOrEmpty(ident) || string.IsNullOrEmpty(dataHash))
        {
            return false;
        }

        if (!_cache.TryGetValue(ident, out var entry))
        {
            return false;
        }

        if (!string.Equals(entry.DataHash, dataHash, StringComparison.Ordinal))
        {
            return false;
        }

        metrics = entry.Metrics;
        return true;
    }

    public void StoreMetrics(string ident, string dataHash, PairPerformanceMetrics metrics)
    {
        if (string.IsNullOrEmpty(ident) || string.IsNullOrEmpty(dataHash))
        {
            return;
        }

        _cache[ident] = new CacheEntry(dataHash, metrics);
    }

    public void Clear(string ident)
    {
        if (string.IsNullOrEmpty(ident))
        {
            return;
        }

        _cache.TryRemove(ident, out _);
    }

    public void ClearAll()
    {
        _cache.Clear();
    }
}
