-- Copyright (c) 2026 Huawei Technologies Co., Ltd.
-- openUBMC is licensed under Mulan PSL v2.
-- You can use this software according to the terms and conditions of the Mulan PSL v2.
-- You may obtain a copy of Mulan PSL v2 at: http://license.coscl.org.cn/MulanPSL2
-- THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
-- EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
-- MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
-- See the Mulan PSL v2 for more details.
local cjson = require 'cjson'
local DPU_CARD_MDB_PATH <const> = "/bmc/kepler/Systems/1/PCIeDevices/PCIeCards/DPUCards/"
local DPU_CARD_MDB_INTF <const> = "bmc.kepler.Systems.PCIeDevices.PCIeCard"

local m = {}

local function get_name_by_slot(list, slot)
    for _, v in pairs(list) do
        if v.SlotID == slot then
            return v.Name
        end
    end
end

function m.delete_redundant_sdi_obj(Input)
    local ordered_input
    if not Input or string.len(Input) == 0 then 
        return cjson.json_object_new_object() 
    else 
        ordered_input = cjson.json_object_ordered_decode(Input) 
    end
    local result = cjson.json_object_new_array()
    local network_adapters = cjson.json_object_new_array()
    local sdis = cjson.json_object_new_array()
    --先归类，避免返回数组里面有nil
    for _, v in pairs(ordered_input) do
        if v.AssetType == 'SDI Card' then
            sdis[#sdis + 1] = v
        elseif v.AssetType == 'NetworkAdapter' then
            network_adapters[#network_adapters + 1] = v
        else
            result[#result + 1] = v
        end
    end
    --去除sdi卡的网卡对象
    local dpucards = mdb.get_sub_objects(bus, DPU_CARD_MDB_PATH, DPU_CARD_MDB_INTF)
    local name, slot
    for _, sdi in pairs(sdis) do
        slot = tonumber(string.match(sdi.AssetName, 'PCIeCard(%d+)'))
        name = get_name_by_slot(dpucards, slot)
        for key, network_adapter in pairs(network_adapters) do
            if network_adapter.AssetName == name then
                network_adapters[key] = nil
                break
            end
        end
        result[#result + 1] = sdi
    end 
    --合并
    for _, network_adapter in pairs(network_adapters) do
        if network_adapter then
            result[#result + 1] = network_adapter
        end
    end
    return result
end

return m
