using System;
using System.Runtime.InteropServices;

namespace AdvChkSys.Util
{
    /// <summary>
    /// Provides utility methods for calculating optimal cache capacities based on system memory.
    /// </summary>
    public static class CacheCapacityHelper
    {
        /// <summary>
        /// Calculates the maximum number of chunks that can fit in available memory.
        /// </summary>
        /// <param name="chunkWidth">Chunk width (cells)</param>
        /// <param name="chunkHeight">Chunk height (cells)</param>
        /// <param name="elementSize">Size of a single element in bytes (e.g., use sizeof(byte) or Marshal.SizeOf(typeof(T)))</param>
        /// <param name="safetyFactor">Fraction of available memory to use (0.8 = 80%)</param>
        public static int CalculateChunkCapacity(int chunkWidth, int chunkHeight, int elementSize, double safetyFactor = 0.8)
        {
            ulong availableBytes = MemoryHelper.GetAvailableMemoryBytes();
            ulong usableBytes = (ulong)(availableBytes * safetyFactor);

            int bytesPerChunk = chunkWidth * chunkHeight * elementSize;
            if (bytesPerChunk == 0) bytesPerChunk = 1; // avoid div by zero

            ulong maxChunks = usableBytes / (ulong)bytesPerChunk;
            return (int)Math.Max(1, Math.Min(maxChunks, int.MaxValue));
        }
    }
}