using System;
using System.Collections.Generic;
using System.Linq;

namespace RevitEstimate.ElectricalModule
{
    public class ElectricalDsrCalculator
    {
        // 1. EXHAUSTIVE MASTER DATABASE OF CPWD DSR E&M 2025 & NDSR RATES
        public static List<ElectricalDsrItem> GetMasterDsrRates()
        {
            return new List<ElectricalDsrItem>
            {
                // ================= SUB-HEAD - I : INTERNAL WIRING =================
                new ElectricalDsrItem { CategoryGroup = "Internal Wiring", DsrCode = "1.10.3", Description = "Wiring for light/fan/exhaust/call bell point with 1.5 sq.mm FRLS/HFFR PVC insulated copper conductor... Group - C", Unit = "Point", Rate = 1704.00 },
                new ElectricalDsrItem { CategoryGroup = "Internal Wiring", DsrCode = "1.11", Description = "Wiring for twin control light point with 1.5 sq.mm FRLS/HFFR PVC insulated copper conductor...", Unit = "Point", Rate = 1803.00 },
                new ElectricalDsrItem { CategoryGroup = "Internal Wiring", DsrCode = "1.55.3", Description = "Wiring for group controlled (looped) light/fan point (without independent switch etc.) with 1.5 sq. mm FRLS...", Unit = "Point", Rate = 858.00 },
                new ElectricalDsrItem { CategoryGroup = "Internal Wiring", DsrCode = "1.14.1", Description = "Wiring for circuit/ submain... 2 X 1.5 sq. mm + 1 X 1.5 sq. mm earth wire", Unit = "Metre", Rate = 267.00 },
                new ElectricalDsrItem { CategoryGroup = "Internal Wiring", DsrCode = "1.14.2", Description = "Wiring for circuit/ submain... 2 X 2.5 sq. mm + 1 X 2.5 sq. mm earth wire", Unit = "Metre", Rate = 311.00 },
                new ElectricalDsrItem { CategoryGroup = "Internal Wiring", DsrCode = "1.14.3", Description = "Wiring for circuit/ submain... 2 X 4 sq. mm + 1 X 4 sq. mm earth wire", Unit = "Metre", Rate = 373.00 },
                new ElectricalDsrItem { CategoryGroup = "Internal Wiring", DsrCode = "1.14.4", Description = "Wiring for circuit/ submain... 2 X 6 sq. mm + 1 X 4 sq. mm earth wire", Unit = "Metre", Rate = 482.00 },
                new ElectricalDsrItem { CategoryGroup = "Internal Wiring", DsrCode = "1.14.9", Description = "Wiring for circuit/ submain... 4 x 6 sq.mm + 2 x 6 sq.mm. earth wire", Unit = "Metre", Rate = 813.00 },
                new ElectricalDsrItem { CategoryGroup = "Internal Wiring", DsrCode = "1.14.6", Description = "Wiring for circuit/ submain... 2 x 16 sq.mm + 1 x 6 sq.mm. earth wire", Unit = "Metre", Rate = 772.00 },
                new ElectricalDsrItem { CategoryGroup = "Internal Wiring", DsrCode = "1.14.10", Description = "Wiring for circuit/ submain... 4 x 10 sq.mm + 2 x 6 sq.mm. earth wire", Unit = "Metre", Rate = 1078.00 },
                new ElectricalDsrItem { CategoryGroup = "Internal Wiring", DsrCode = "1.14.11", Description = "Wiring for circuit/ submain... 4 x 16 sq.mm + 2 x 6 sq.mm. earth wire", Unit = "Metre", Rate = 1454.00 },
                new ElectricalDsrItem { CategoryGroup = "Internal Wiring", DsrCode = "1.31", Description = "Supplying and fixing suitable size GI box with modular plate... 3 pin 5/6 A modular socket outlet and 5/6 amps modular switch", Unit = "Each", Rate = 545.00 },
                new ElectricalDsrItem { CategoryGroup = "Internal Wiring", DsrCode = "1.32", Description = "Supplying and fixing suitable size GI box with modular plate... 6 pin 5/6 & 15/16 amps modular socket outlet and 15/16 amps modular switch", Unit = "Each", Rate = 659.00 },
                new ElectricalDsrItem { CategoryGroup = "Internal Wiring", DsrCode = "1.56", Description = "Supplying and fixing suitable size GI box... 2 nos. 3 pin 5/6 A modular socket outlet and 2 nos. 5/6 A modular switch", Unit = "Each", Rate = 676.00 },
                new ElectricalDsrItem { CategoryGroup = "Internal Wiring", DsrCode = "1.57", Description = "Supplying & fixing suitable size GI box wih modular plate... 25 A modular socket outlet and 25 A modular SP MCB", Unit = "Each", Rate = 807.00 },
                new ElectricalDsrItem { CategoryGroup = "Internal Wiring", DsrCode = "1.25", Description = "Supplying and fixing two module stepped type electronic fan regulator on the existing modular plate switch box", Unit = "Each", Rate = 402.00 },
                new ElectricalDsrItem { CategoryGroup = "Internal Wiring", DsrCode = "1.26", Description = "Supplying and fixing modular blanking plate on the existing modular plate & switch box", Unit = "Each", Rate = 47.00 },
                new ElectricalDsrItem { CategoryGroup = "Internal Wiring", DsrCode = "1.24.1", Description = "Supplying and fixing following modular switch/ socket... 5/6 A switch", Unit = "Each", Rate = 103.00 },
                new ElectricalDsrItem { CategoryGroup = "Internal Wiring", DsrCode = "1.24.4", Description = "Supplying and fixing following modular switch/ socket... 3 pin 5/6 A socket outlet", Unit = "Each", Rate = 148.00 },
                new ElectricalDsrItem { CategoryGroup = "Internal Wiring", DsrCode = "1.33", Description = "Supplying and fixing 3 pin, 5 A ceiling rose on the existing junction box/ wooden block", Unit = "Each", Rate = 104.00 },
                new ElectricalDsrItem { CategoryGroup = "Internal Wiring", DsrCode = "1.35", Description = "Installation ,Testing, Commissioning of wall bracket /ceiling fittings of all sizes and shapes", Unit = "Each", Rate = 151.00 },
                new ElectricalDsrItem { CategoryGroup = "Internal Wiring", DsrCode = "DSR Civil 10.18", Description = "Providing and fixing circular/ Hexagonal cast iron or M.S. sheet box for ceiling fan clamp...", Unit = "Each", Rate = 220.65 },
                new ElectricalDsrItem { CategoryGroup = "Internal Wiring", DsrCode = "1.47", Description = "Supplying and fixing extra down rod of 10 cm length G.I. pipe, 15 mm dia, heavy gauge", Unit = "Each", Rate = 46.00 },
                new ElectricalDsrItem { CategoryGroup = "Internal Wiring", DsrCode = "1.50.1", Description = "Supplying of exhaust fan complete with gravity louver... Upto 450 mm sweep", Unit = "Each", Rate = 556.00 },
                new ElectricalDsrItem { CategoryGroup = "Internal Wiring", DsrCode = "1.50.2", Description = "Supplying of exhaust fan complete with gravity louver... 510 mm sweep", Unit = "Each", Rate = 643.00 },
                new ElectricalDsrItem { CategoryGroup = "Internal Wiring", DsrCode = "1.51", Description = "Extra for fixing the Louvers/ shutters complete with frame for exhaust fans of all sizes.", Unit = "Each", Rate = 260.00 },

                // ================= SUB-HEAD II - FANS & LIGHT FIXTURES =================
                new ElectricalDsrItem { CategoryGroup = "Fans & Light Fixtures", DsrCode = "8.8.4", Description = "LED Panel light 2x2 ft. 36 watt (System lumen efficacy>135 lm/Watt)", Unit = "Each", Rate = 3997.00 },
                new ElectricalDsrItem { CategoryGroup = "Fans & Light Fixtures", DsrCode = "8.8.3", Description = "LED Panel light 2x2 ft. 22 watt (System lumen efficacy >135 lm/Watt)", Unit = "Each", Rate = 3581.00 },
                new ElectricalDsrItem { CategoryGroup = "Fans & Light Fixtures", DsrCode = "NDSR L1", Description = "Supply of LED 4ft 40W LED Tube light with a nominal system lumen output of 4000 lumens", Unit = "Each", Rate = 0.00 },
                new ElectricalDsrItem { CategoryGroup = "Fans & Light Fixtures", DsrCode = "NDSR L2", Description = "Supply of LED 4ft Batten recess/suspended linear connected", Unit = "Each", Rate = 0.00 },
                new ElectricalDsrItem { CategoryGroup = "Fans & Light Fixtures", DsrCode = "8.11.1", Description = "LED Batten light 18- 22 Watt (System lumen efficacy >135 lm/Watt)", Unit = "Each", Rate = 787.00 },
                new ElectricalDsrItem { CategoryGroup = "Fans & Light Fixtures", DsrCode = "NDSR L3", Description = "Supply of LED 4ft Batten recess linear connected with a nominal system lumen output of 2000 lumens", Unit = "Each", Rate = 0.00 },
                new ElectricalDsrItem { CategoryGroup = "Fans & Light Fixtures", DsrCode = "8.3.2", Description = "LED Down lighter (SMD Type) 8-10 watt", Unit = "Each", Rate = 657.00 },
                new ElectricalDsrItem { CategoryGroup = "Fans & Light Fixtures", DsrCode = "8.3.3", Description = "LED Down lighter (SMD Type) 12-15 watt", Unit = "Each", Rate = 756.00 },
                new ElectricalDsrItem { CategoryGroup = "Fans & Light Fixtures", DsrCode = "NDSR L4", Description = "Supply of Surface mounting square 18Watt to 20 Watt", Unit = "Each", Rate = 0.00 },
                new ElectricalDsrItem { CategoryGroup = "Fans & Light Fixtures", DsrCode = "NDSR L5", Description = "Supply of Recess mounting round 20Watt to 24 Watt", Unit = "Each", Rate = 0.00 },
                new ElectricalDsrItem { CategoryGroup = "Fans & Light Fixtures", DsrCode = "NDSR L6", Description = "Supply & fixing of water tight oblong 10 watt LED Bulkhead luminaire", Unit = "Each", Rate = 2440.08 },
                new ElectricalDsrItem { CategoryGroup = "Fans & Light Fixtures", DsrCode = "NDSR L7", Description = "Supplying of LED mirror light luminaire with 10W watt", Unit = "Each", Rate = 0.00 },
                new ElectricalDsrItem { CategoryGroup = "Fans & Light Fixtures", DsrCode = "NDSR L8", Description = "Supply of LED Flood light 70 Watt", Unit = "Each", Rate = 0.00 },
                new ElectricalDsrItem { CategoryGroup = "Fans & Light Fixtures", DsrCode = "NDSR L11", Description = "Supply and fixing of round 13 Watt, LED Spot Light", Unit = "Each", Rate = 0.00 },
                new ElectricalDsrItem { CategoryGroup = "Fans & Light Fixtures", DsrCode = "1.34", Description = "Supplying and fixing brass batten/ angle holder including connection", Unit = "Each", Rate = 131.00 },
                new ElectricalDsrItem { CategoryGroup = "Fans & Light Fixtures", DsrCode = "9.2.3", Description = "Brush Less Direct Current (BLDC) Fan with Remote Supply, Installation", Unit = "Each", Rate = 2695.00 },
                new ElectricalDsrItem { CategoryGroup = "Fans & Light Fixtures", DsrCode = "NDSR F1", Description = "Supplying, erection, connecting, testing and commissioning of 400 mm Wall Fan", Unit = "Each", Rate = 0.00 },
                new ElectricalDsrItem { CategoryGroup = "Fans & Light Fixtures", DsrCode = "NDSR F2", Description = "Supplying of following size exhaust fan... 300mm EXHAUST FAN", Unit = "Each", Rate = 0.00 },
                new ElectricalDsrItem { CategoryGroup = "Fans & Light Fixtures", DsrCode = "NDSR CO", Description = "Supply of Single Phase Automatic Changeover with Current Limiter 30A/15A", Unit = "Each", Rate = 0.00 },

                // ================= SUBHEAD- III: DISTRIBUTION BOARD =================
                new ElectricalDsrItem { CategoryGroup = "Distribution Board", DsrCode = "NDSR DB1", Description = "Providing and fixing... 63 A,25KA,FP MCCB", Unit = "Each", Rate = 0.00 },
                new ElectricalDsrItem { CategoryGroup = "Distribution Board", DsrCode = "2.2.13", Description = "Providing and fixing... 100 A,30KA,FPMCCB", Unit = "Each", Rate = 8127.00 },
                new ElectricalDsrItem { CategoryGroup = "Distribution Board", DsrCode = "2.2.14", Description = "Providing and fixing... 125 A,36KA,FPMCCB", Unit = "Each", Rate = 8644.00 },
                new ElectricalDsrItem { CategoryGroup = "Distribution Board", DsrCode = "2.2.15", Description = "Providing and fixing... 200 A, 36KA,FPMCCB", Unit = "Each", Rate = 15206.00 },
                new ElectricalDsrItem { CategoryGroup = "Distribution Board", DsrCode = "2.3.1", Description = "Supplying and fixing... 6 Way Double Door DB", Unit = "Nos.", Rate = 2390.00 },
                new ElectricalDsrItem { CategoryGroup = "Distribution Board", DsrCode = "2.3.2", Description = "Supplying and fixing... 8 way, Double door DB", Unit = "Nos.", Rate = 2573.00 },
                new ElectricalDsrItem { CategoryGroup = "Distribution Board", DsrCode = "2.3.3", Description = "Supplying and fixing... 12 way, Double Door DB", Unit = "Nos.", Rate = 2315.00 },
                new ElectricalDsrItem { CategoryGroup = "Distribution Board", DsrCode = "2.3.4", Description = "Supplying and fixing... 16 way, Double Door DB", Unit = "Nos.", Rate = 3141.00 },
                new ElectricalDsrItem { CategoryGroup = "Distribution Board", DsrCode = "2.4.1", Description = "Supplying and fixing... 4 Way Double door (Horizontal TPN)", Unit = "Nos.", Rate = 4377.00 },
                new ElectricalDsrItem { CategoryGroup = "Distribution Board", DsrCode = "2.4.2", Description = "Supplying and fixing... 6 way Double door (Horizontal TPN)", Unit = "Nos.", Rate = 5299.00 },
                new ElectricalDsrItem { CategoryGroup = "Distribution Board", DsrCode = "2.5.1", Description = "Supplying and fixing... 4 way (4 + 12), Double door (Vertical TPN)", Unit = "Nos.", Rate = 7951.00 },
                new ElectricalDsrItem { CategoryGroup = "Distribution Board", DsrCode = "2.5.2", Description = "Supplying and fixing... 8 way (4 + 24), Double door (Vertical TPN)", Unit = "Nos.", Rate = 10165.00 },
                new ElectricalDsrItem { CategoryGroup = "Distribution Board", DsrCode = "NDSR DB6", Description = "Supplying and fixing... 63 amps SP MCB in existing MCB DB", Unit = "Each", Rate = 0.00 },
                new ElectricalDsrItem { CategoryGroup = "Distribution Board", DsrCode = "NDSR DB9", Description = "Supplying and fixing... 40 amps TP MCB", Unit = "Each", Rate = 0.00 },
                new ElectricalDsrItem { CategoryGroup = "Distribution Board", DsrCode = "NDSR DB10", Description = "Supplying and fixing... 63 amps TP MCB", Unit = "Each", Rate = 0.00 },
                new ElectricalDsrItem { CategoryGroup = "Distribution Board", DsrCode = "NDSR DB11", Description = "Supplying and fixing... 40 amps 4P MCB", Unit = "Each", Rate = 0.00 },
                new ElectricalDsrItem { CategoryGroup = "Distribution Board", DsrCode = "NDSR DB12", Description = "Supplying and fixing... 63 amps 4P MCB", Unit = "Each", Rate = 0.00 },
                new ElectricalDsrItem { CategoryGroup = "Distribution Board", DsrCode = "2.12.1", Description = "Supplying and fixing double pole isolator... 40 amps", Unit = "Each", Rate = 435.00 },
                new ElectricalDsrItem { CategoryGroup = "Distribution Board", DsrCode = "2.12.2", Description = "Supplying and fixing double pole isolator... 63 amps", Unit = "Each", Rate = 527.00 },
                new ElectricalDsrItem { CategoryGroup = "Distribution Board", DsrCode = "2.14.1", Description = "Supplying and fixing double pole RCCB (30mA)... 25 amps", Unit = "Nos", Rate = 2028.00 },
                new ElectricalDsrItem { CategoryGroup = "Distribution Board", DsrCode = "2.10.1", Description = "Supplying and fixing 5 amps to 32 amps 'C' curve MCB... Single pole", Unit = "Nos.", Rate = 285.00 },
                new ElectricalDsrItem { CategoryGroup = "Distribution Board", DsrCode = "2.10.3", Description = "Supplying and fixing 5 amps to 32 amps 'C' curve MCB... Double pole", Unit = "Nos.", Rate = 696.00 },
                new ElectricalDsrItem { CategoryGroup = "Distribution Board", DsrCode = "2.10.4", Description = "Supplying and fixing 5 amps to 32 amps 'C' curve MCB... Triple pole", Unit = "Nos.", Rate = 1007.00 },
                new ElectricalDsrItem { CategoryGroup = "Distribution Board", DsrCode = "2.11", Description = "Supplying and fixing single pole blanking plate in the existing MCB DB", Unit = "Each", Rate = 14.00 },
                new ElectricalDsrItem { CategoryGroup = "Distribution Board", DsrCode = "NDSR M1", Description = "Supplying and fixing 1P LCD Energy Meter 5-30A with BOX", Unit = "Each", Rate = 0.00 },
                new ElectricalDsrItem { CategoryGroup = "Distribution Board", DsrCode = "2.18", Description = "Supplying and fixing 20 A, 240 V, SPN Industrial type socket outlet with MCB and enclosure", Unit = "Each", Rate = 1621.00 },
                new ElectricalDsrItem { CategoryGroup = "Distribution Board", DsrCode = "14.15.2", Description = "Supplying and laying DWC HDPE pipe... 90 mm dia (OD-90 mm & ID-76 mm nominal)", Unit = "Metre", Rate = 170.00 },

                // ================= SUBHEAD - V - EARTHING =================
                new ElectricalDsrItem { CategoryGroup = "Earthing", DsrCode = "2.21", Description = "Providing and fixing M.V. danger notice plate of 200 mm X 150 mm, made of mild steel", Unit = "Each", Rate = 315.00 },
                new ElectricalDsrItem { CategoryGroup = "Earthing", DsrCode = "5.2", Description = "Earthing with G.I. earth pipe 4.5 metre long, 40 mm dia including accessories", Unit = "Nos.", Rate = 6855.00 },
                new ElectricalDsrItem { CategoryGroup = "Earthing", DsrCode = "5.4", Description = "Earthing with G.I. earth plate 600 mm x 600 mm x 6 mm thick including accessories", Unit = "Set", Rate = 8351.00 },
                new ElectricalDsrItem { CategoryGroup = "Earthing", DsrCode = "5.6", Description = "Earthing with copper earth plate 600 mm X 600 mm X 3 mm thick including accessories", Unit = "Set", Rate = 13838.00 },
                new ElectricalDsrItem { CategoryGroup = "Earthing", DsrCode = "5.8", Description = "Supplying and laying 25 mm X 5 mm copper strip at 0.50 metre below ground as strip earth electrode", Unit = "Meter", Rate = 972.00 },
                new ElectricalDsrItem { CategoryGroup = "Earthing", DsrCode = "5.9", Description = "Supplying and laying 25 mm X 5 mm G.I strip at 0.50 metre below ground as strip earth electrode", Unit = "Meter", Rate = 160.00 },
                new ElectricalDsrItem { CategoryGroup = "Earthing", DsrCode = "5.12", Description = "Providing and laying earth connection from earth electrode with 6 SWG dia G.I. Wire in 15 mm dia G.I. pipe", Unit = "Metre", Rate = 313.00 },
                new ElectricalDsrItem { CategoryGroup = "Earthing", DsrCode = "5.14", Description = "Providing and fixing 25 mm X 5 mm copper strip on surface or in recess for connections", Unit = "Meter", Rate = 1162.00 },
                new ElectricalDsrItem { CategoryGroup = "Earthing", DsrCode = "5.15", Description = "Providing and fixing 25 mm x 5 mm G.I. strip on surface or in recess for connections", Unit = "Meter", Rate = 244.00 }
            };
        }

        // 2. GENERATE FINAL ESTIMATE WITH SORTING LOGIC
        public static List<ElectricalDsrItem> GenerateEstimate(List<RoomElectricalData> rooms, double floorToFloorHeightMeters)
        {
            var estimate = GetMasterDsrRates();
            foreach (var item in estimate)
            {
                item.Qty = 0.00;
            }

            // Aggregation Variables
            int totalLightPoints = 0, totalCeilingFans = 0, totalWallFans = 0;
            int total5PinSockets = 0, totalKitchenSockets = 0, totalHeavyPower = 0;

            double total1_5_WireMeters = 0;
            double total2_5_WireMeters = 0;
            double total4_WireMeters = 0;

            int total6WayDB = 0, total8WayDB = 0, total12WayDB = 0, total16WayDB = 0;
            int totalRoomMCBs_SP = 0;
            int totalMasterMCBs_DP = 0;

            var activeRooms = rooms.Where(r => r.IsRoomActive && r.IsFlatEnabled).ToList();

            // 1. Calculate General Points & Wires
            foreach (var room in activeRooms)
            {
                totalLightPoints += room.LightPointQty;
                totalCeilingFans += room.CeilingFanQty;
                totalWallFans += room.WallFanQty;
                total5PinSockets += room.General5PinSocketQty;
                totalKitchenSockets += room.KitchenCounterSocketQty;
                totalHeavyPower += room.HeavyPowerSocketQty;

                total1_5_WireMeters += (room.LightPointQty * 2.5);
                total2_5_WireMeters += (room.General5PinSocketQty * 6.0) + (room.KitchenCounterSocketQty * 8.0);
                total4_WireMeters += (room.HeavyPowerSocketQty * 12.0);
            }

            // 2. Dynamic DB & MCB Logic Grouped by Flat
            var flatGroups = activeRooms.GroupBy(r => r.FlatNumber);
            foreach (var flat in flatGroups)
            {
                int roomCount = flat.Count();
                totalRoomMCBs_SP += roomCount;
                totalMasterMCBs_DP += 1;

                int waysRequired = roomCount + 2 + 1;
                if (waysRequired <= 6) total6WayDB++;
                else if (waysRequired <= 8) total8WayDB++;
                else if (waysRequired <= 12) total12WayDB++;
                else total16WayDB++;
            }

            // Helper function to assign quantities (strictly prefers DSR items over NDSR)
            void UpdateQty(string dsrCode, double qty)
            {
                var targetItem = estimate.FirstOrDefault(x => x.DsrCode == dsrCode);
                if (targetItem != null) targetItem.Qty = qty;
            }

            // --- Updating Quantities ---
            UpdateQty("1.10.3", totalLightPoints + totalCeilingFans + totalWallFans);
            UpdateQty("1.14.1", total1_5_WireMeters);
            UpdateQty("1.14.2", total2_5_WireMeters);
            UpdateQty("1.14.3", total4_WireMeters);
            UpdateQty("1.31", total5PinSockets);
            UpdateQty("1.32", totalKitchenSockets);
            UpdateQty("1.57", totalHeavyPower);

            UpdateQty("DSR Civil 10.18", totalCeilingFans);
            UpdateQty("9.2.3", totalCeilingFans);
            UpdateQty("1.25", totalCeilingFans);

            int battenQty = (int)(totalLightPoints * 0.6);
            int downLighterQty = totalLightPoints - battenQty;
            UpdateQty("8.11.1", battenQty); // Standard DSR preferred
            UpdateQty("8.3.2", downLighterQty); // Standard DSR preferred

            UpdateQty("2.3.1", total6WayDB);
            UpdateQty("2.3.2", total8WayDB);
            UpdateQty("2.3.3", total12WayDB);
            UpdateQty("2.3.4", total16WayDB);
            UpdateQty("2.10.1", totalRoomMCBs_SP);
            UpdateQty("2.10.3", totalMasterMCBs_DP);

            int totalMainEarthingSets = 2;
            UpdateQty("5.4", totalMainEarthingSets);
            UpdateQty("5.9", totalMainEarthingSets * 10);
            UpdateQty("5.12", totalMainEarthingSets * 5);

            // ==========================================
            // 3. SORTING LOGIC AS PER REQUIREMENT
            // ==========================================
            var finalSortedEstimate = estimate
                // Priority 1: Greater than 0 quantity items come first
                .OrderByDescending(x => x.Qty > 0)
                // Priority 2: Standard DSR (0) preferred over NDSR (1)
                .ThenBy(x => x.DsrCode.ToUpper().Contains("NDSR") || x.DsrCode.ToUpper().Contains("NS") ? 1 : 0)
                // Priority 3: Keep grouped by Sub-Head / Category logically
                .ThenBy(x => x.CategoryGroup)
                .ToList();

            // 4. Update Serial Numbers Sequentially
            int serial = 1;
            foreach (var item in finalSortedEstimate)
            {
                item.SrNo = serial.ToString();
                serial++;
            }

            return finalSortedEstimate;
        }
    }
}