using System;

namespace QuantEngine.Core.Domain
{
    public static class KrxTickNormalizer
    {
        private static readonly (double Limit, int Tick)[] KrxTickTable = new (double, int)[]
        {
            (2000, 1),
            (5000, 5),
            (20000, 10),
            (50000, 50),
            (200000, 100),
            (500000, 500),
            (double.PositiveInfinity, 1000)
        };

        public static int GetTickUnit(double price)
        {
            foreach (var (limit, tick) in KrxTickTable)
            {
                if (price < limit)
                {
                    return tick;
                }
            }
            return 1000;
        }

        public static double NormalizeTick(double price)
        {
            if (price <= 0) return 0;
            int tick = GetTickUnit(price);
            
            // Round to nearest tick unit
            double remainder = price % tick;
            if (remainder == 0) return price;

            if (remainder >= tick / 2.0)
            {
                return price + (tick - remainder);
            }
            else
            {
                return price - remainder;
            }
        }
    }
}
