-- 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 class = require('mc.class')
local _, skynet = pcall(require, 'skynet')
local hwproxy_error = require('hwproxy.errors')
local log = require('mc.logging')
local dispatch = require('dispatch')

local CLASS_JTAG_SWITCH = 'JtagSwitch'

local SCANNER_INTERFACE <const> = 'bmc.kepler.Scanner'

-- 根据对象名称提取class_name
local function get_class_type(object_name)
    return string.match(object_name, '(.-)_')
end

---@class hwproxy_objects
---@field chips table<chip>
local hwproxy_objects = class()

function hwproxy_objects:ctor(bus_object_name)
    -- buses/chips/mux对象信息和topo缓存保留
    self.buses = {}
    self.chip_objs = {}
    self.mux_data = {}
    self.topo_data = {}
    -- 保存accessor/scanner与chip对象的关系,弱引用
    self.accessor_ref_chip = {}
    self.scanner_ref_chip = {}
    -- resources/debounce对象信息在本级分发完成后清除缓存
    self.resources = {}
    self.debounce_objects = {}
    self.delete_chips = {}
    self.dft_list = {}
    self.smc_dfx_info_list = {}

    self.is_main_app = bus_object_name == nil
    self.dispatch = dispatch.new(self.is_main_app, bus_object_name)

    -- 器件拓扑,相同器件合并后的效果
    self.chip_topo = {}
    self.chips = {}
end

function hwproxy_objects:clean_up(position)
    self.resources[position] = nil
    self.debounce_objects[position] = nil
    self.smc_dfx_info_list[position] = nil
end

function hwproxy_objects:get_object_name_from_path(obj)
    return string.match(obj.path, '.*/(.*)')
end

function hwproxy_objects:get_vchip_name_from_path(obj)
    return 'VChip_' .. self:get_object_name_from_path(obj)
end

function hwproxy_objects:check_chip_exist(chip_name)
    if not self.chips[chip_name] then
        error(hwproxy_error.chip_not_exist_error())
    end
end

-- 对象添加处理
function hwproxy_objects:bus_object_handle(class_name, object, position)
    self.buses[object.name] = self:new_bus(object)
end

function hwproxy_objects:chip_object_handle(class_name, object, position)
    self.chip_objs[object.name] = object
end

function hwproxy_objects:resource_object_handle(class_name, object, position)
    -- 缓存resource对象数据,complete时进行处理
    self.resources[position] = self.resources[position] or {}
    self.resources[position][object.Chip] = self.resources[position][object.Chip] or {}
    table.insert(self.resources[position][object.Chip], object)
end

function hwproxy_objects:mux_object_handle(class_name, object, position)
    -- 缓存mux对象数据,complete时进行处理
    self.mux_data = self.mux_data or {}
    self.mux_data[object.name] = self.mux_data[object.name] or {}
    self.mux_data[object.name].channel_id = object.ChannelId or 0
end

function hwproxy_objects:debounce_object_handle(class_name, object, position)
    -- 缓存debounce对象数据,complete时与resource进行处理
    self.debounce_objects[position] = self.debounce_objects[position] or {}
    self.debounce_objects[position][object.name] = object
end

function hwproxy_objects:dft_object_handle(class_name, object, position)
    object.Slot = tonumber(string.sub(position, -2)) -- 截取position后两位做为slot
    self.dft_list[object.name] = object
end

function hwproxy_objects:smc_dfx_info_handle(class_name, object, position)
    self.smc_dfx_info_list[position] = self.smc_dfx_info_list[position] or {}
    self.smc_dfx_info_list[position][object.Chip] = self.smc_dfx_info_list[position][object.Chip] or {}
    table.insert(self.smc_dfx_info_list[position][object.Chip], object)
end

-- 对象删除处理,删除accessor_ref_chip缓存
function hwproxy_objects:on_delete_object(class_name, object, position)
    if class_name == 'Accessor' then
        local chip_obj = self.accessor_ref_chip[object.name]
        if chip_obj then
            chip_obj.accessors[object.name] = nil
            self.accessor_ref_chip[object.name] = nil
        end
    end

    if class_name == 'Scanner' then
        local chip_obj = self.scanner_ref_chip[object.name]
        if chip_obj then
            chip_obj.scanners[object.name]:delete_resource(object.name)
            chip_obj.scanners[object.name] = nil
            self.scanner_ref_chip[object.name] = nil
        end
        local scanner_if = object[SCANNER_INTERFACE]
        if scanner_if and type(scanner_if.clear_error) == 'function' then
            scanner_if:clear_error('Value')
        end
    end

    self.delete_chips[position] = self.delete_chips[position] or {}
    if not self.chips[object.name] then
        return
    end

    pcall(function()
        local default_addr = get_class_type(object.name) == CLASS_JTAG_SWITCH and 0xfe or 0xff
        local address = self.chips[object.name].driver.address or default_addr
        local pre_chip = self.chips[object.name].l_chip
        if pre_chip then
            local channel_id = self.chips[object.name].channel_id
            local chip_topo_obj = self.chip_topo[pre_chip.name][channel_id][address]
            chip_topo_obj.ref_count = chip_topo_obj.ref_count - 1
            chip_topo_obj.chip.ref_count = chip_topo_obj.chip.ref_count - 1
            if chip_topo_obj.ref_count == 0 then
                self.chip_topo[pre_chip.name][channel_id][address] = nil
            end
        else
            local host_bus = self.chips[object.name].host_bus
            local chip_topo_obj = self.chip_topo[host_bus.name][address]
            chip_topo_obj.ref_count = chip_topo_obj.ref_count - 1
            chip_topo_obj.chip.ref_count = chip_topo_obj.chip.ref_count - 1
            if chip_topo_obj.ref_count == 0 then
                self.chip_topo[host_bus.name][address] = nil
            end
        end
    end)
    table.insert(self.delete_chips[position], object.name)
end

function hwproxy_objects:process_resources_for_position(position)
    for chip_name, resource_list in pairs(self.resources[position] or {}) do
        if not self.chips[chip_name] then
            log:error('No chip object: %s, add resources failed', chip_name)
            goto continue
        end
        for _, obj in pairs(resource_list) do
            local debounce_object = self.debounce_objects[position] and self.debounce_objects[position][obj.Debounce]
                or nil
            if obj.class_name == 'Accessor' then
                self.chips[chip_name]:add_accessor(obj)
                self.accessor_ref_chip[obj.name] = self.chips[chip_name]
            else
                self.chips[chip_name]:add_scanner(obj, debounce_object)
                self.scanner_ref_chip[obj.name] = self.chips[chip_name]
            end
            if not self.is_main_app and obj.need_register then
                skynet.send('.hwproxy', 'lua', 'object_register', obj.name, chip_name)
            end
        end
        ::continue::
    end
end

function hwproxy_objects:notify_monitor_and_cleanup(position, monitor_service)
    if not self.is_main_app then
        log:debug(
            'work service finsh to add object complete, bus_name: %s, position: %s',
            self.dispatch.bus_object_name,
            position
        )
        if not monitor_service then
            log:error(
                'get register monitor_service fail, bus_name: %s, position: %s',
                self.dispatch.bus_object_name,
                position
            )
        else
            skynet.send(monitor_service, 'lua', 'set_work_monitor_status', self.dispatch.bus_object_name, position)
        end
    end
    self:clean_up(position)
end
-- 对象添加完成处理
function hwproxy_objects:on_add_object_complete(position, monitor_service)
    if not self.is_main_app then
        log:debug(
            'work service start to add object complete, bus_name: %s, position: %s',
            self.dispatch.bus_object_name,
            position
        )
    end
    if not self.topo_data[position] then
        self:clean_up(position)
        log:raise('topology data not exist, position: %s', position)
    end
    self.dispatch:generate_topo_link(
        self,
        self.buses,
        self.chip_objs,
        self.mux_data,
        self.topo_data[position],
        position
    )

    for chip_name, obj_list in pairs(self.smc_dfx_info_list[position] or {}) do
        local chip = self.chips[chip_name]
        if chip then
            for _, obj in ipairs(obj_list) do
                chip:add_smc_dfx_info(obj)
            end
        end
    end

    self:process_resources_for_position(position)

    self:notify_monitor_and_cleanup(position, monitor_service)
end

-- 对象删除完成处理
function hwproxy_objects:on_delete_object_complete(position)
    self:clean_up(position)
    if self.topo_data[position] then
        self.dispatch:remove_topo_link(self.chips, self.topo_data[position])
        self.topo_data[position] = nil
    end

    if self.delete_chips[position] == nil then
        return
    end

    -- 删除chips缓存
    for _, chip_name in pairs(self.delete_chips[position]) do
        self.chips[chip_name] = nil
    end
    self.delete_chips[position] = nil
end

function hwproxy_objects:get_chip_name(obj)
    local chip_name = obj.chip or self:get_object_name_from_path(obj)
    self:check_chip_exist(chip_name)
    return chip_name
end

function hwproxy_objects:get_vchip_name(obj)
    local chip_name = obj.chip or self:get_vchip_name_from_path(obj)
    self:check_chip_exist(chip_name)
    return chip_name
end

function hwproxy_objects:get_bus_name(obj)
    local bus_name = self:get_object_name_from_path(obj)
    return bus_name
end

function hwproxy_objects:get_ref_chip_name(obj)
    local obj_name = self:get_object_name_from_path(obj)
    local object = self.dft_list[obj_name]
    self:check_chip_exist(object.RefChip)
    return object.RefChip
end

return hwproxy_objects