-- 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 hwproxy_objects = require('hwproxy_objects')
local _, skynet = pcall(require, 'skynet')
local hwproxy_error = require('hwproxy.errors')
local bus = require('hwproxy_objects.work_bus')
local object_pool = require('object_pool')
local log = require('mc.logging')
local context = require('mc.context')
local object_defs = require('object_defs')
local hw_wait_access = require('hw_utils.hw_wait_access')
local wait_hw_access = hw_wait_access.wait_hw_access
local ctor_print_info = hw_wait_access.ctor_print_info
local vos = require('utils.vos')

local t_concat = table.concat
local t_unpack = table.unpack

local trace = require('telemetry.trace')

local function empty_cb() end

local function get_class_type(object_name)
    return string.match(object_name, '(.-)_')
end

local work_objects = class(hwproxy_objects)

function work_objects:ctor(bus_object_name)
    self.bus_object_name = bus_object_name
    self.plugins = {}
    self.access_enabled = true
end

function work_objects:new_bus(object)
    if object.name ~= self.bus_object_name then
        error(
            string.format('add unknown bus: work bus name = %s, new bus name = %s', self.bus_object_name, object.name)
        )
    end
    return bus.new(object)
end

function work_objects:on_add_object_complete(position, topo_data, monitor_service)
    self.topo_data[position] = topo_data
    self.super.on_add_object_complete(self, position, monitor_service)
end

-- 对象资源树方法实现
function work_objects:read_write_func(func_name, obj, ctx, ...)
    context.set_context(ctx)
    local span = trace.start_span(
        'hwproxy.work_objects.read_write_func',
        trace.get_status()
                and { ['bus.name'] = self.bus_object_name, ['func.name'] = func_name, ['chip.name'] = obj.path }
            or nil
    )
    if not self.access_enabled then
        span:add_event('Bus inaccessible')
        span:finish()
        log:raise('The Bus access(%s) has been closed, please manually open it!', self.bus_object_name)
    end
    local chip_name = self:get_chip_name(obj)
    local fetch = object_pool.new('fetch', empty_cb, nil, false, nil, ctx)
    if log:getLevel() == log.DEBUG then
        log:debug('Chip %s starts to execute the %s function.', chip_name, func_name)
    end
    local chip_obj = self.chips[chip_name]
    local request_info = ctor_print_info(self.bus_object_name, chip_name, func_name)
    local receive_time = (getmetatable(ctx) == context or type(ctx) == 'table') and ctx.RPCTimeCost
    local read_begin
    if receive_time then
        read_begin = vos.vos_tick_get()
        log:mdbctl_log('from receive to start of operation cost %s ms', read_begin - receive_time)
    end
    chip_obj[func_name](chip_obj, fetch, ctx, ...)
    local obj_def = object_defs[get_class_type(chip_name)]
    local timeout = obj_def and obj_def.request_timeout
    local result = wait_hw_access(fetch, timeout, request_info)
    if read_begin then
        local read_end = vos.vos_tick_get()
        log:mdbctl_log('from start of operation to end of operation cost %s ms', read_end - read_begin)
    end
    span:finish()
    return result
end

function work_objects:monitor_obj(obj, _, action)
    local chip_name = self:get_chip_name(obj)
    local chip_obj = self.chips[chip_name]
    if action == 'start' then
        chip_obj['set_monitored'](chip_obj)
    else
        chip_obj['unset_monitored'](chip_obj)
    end
end

function work_objects:trace_scanner_debounce(object, ctx, action)
    local chip_obj = self.scanner_ref_chip[object.name]
    chip_obj.scanners[object.name]:add_resource_trace_flag(object.name, action)
end

function work_objects:clear_obj_monitored()
    for _, chip_obj in pairs(self.chips) do
        chip_obj:unset_monitored()
    end
end

function work_objects:cpld_upg_request(op, obj, ctx, ...)
    if not self.access_enabled then
        log:raise('The Bus access(%s) has been closed, please manually open it!', self.bus_object_name)
    end
    local fetch = {}
    local args = { ... }
    local chip_name = self:get_chip_name(obj)
    local chip_obj = self.chips[chip_name]
    fetch.run = function()
        return chip_obj.host_bus.stream[op](chip_obj.host_bus.stream, t_unpack(args))
    end
    local request_info = ctor_print_info(self.bus_object_name, chip_name, 'cpld_upg_request')

    chip_obj:cpld_upg_request(fetch)
    local obj_def = object_defs[get_class_type(chip_name)]
    local timeout = obj_def and obj_def.request_timeout
    return wait_hw_access(fetch, timeout, request_info)
end

-- Accessor属性实时读取/写入方法
function work_objects:realtime_read(host_bus, accessor_name, ctx, offset)
    context.set_context(ctx)
    local span = trace.start_span(
        'hwproxy.work_objects.realtime_read',
        trace.get_status() and { ['bus.name'] = self.bus_object_name, ['accessor.name'] = accessor_name } or nil
    )
    if not self.access_enabled then
        span:set_status('error', string.format('Bus %s inaccessible', self.bus_object_name))
        span:finish()
        log:raise('The Bus access(%s) has been closed, please manually open it!', self.bus_object_name)
    end
    local fetch = object_pool.new('fetch', empty_cb, nil, false, nil, ctx)
    local ref_chip = self.accessor_ref_chip[accessor_name]
    if not ref_chip then
        span:add_event(string.format('accessor %s ref chip does not exist', accessor_name))
        span:finish()
        error(hwproxy_error.chip_not_exist_error())
    end
    local request_info = ctor_print_info(self.bus_object_name, ref_chip.name, 'realtime_read')

    ref_chip:realtime_read(accessor_name, fetch, offset)
    local obj_def = object_defs[get_class_type(accessor_name)]
    local timeout = obj_def and obj_def.request_timeout
    local result = wait_hw_access(fetch, timeout, request_info)
    span:finish()
    return result
end

function work_objects:realtime_write(host_bus, accessor_name, ctx, value)
    context.set_context(ctx)
    local span = trace.start_span(
        'hwproxy.work_objects.realtime_write',
        trace.get_status() and { ['bus.name'] = self.bus_object_name, ['accessor.name'] = accessor_name } or nil
    )
    if not self.access_enabled then
        span:set_status('error', string.format('Bus %s inaccessible', self.bus_object_name))
        log:raise('The Bus access(%s) has been closed, please manually open it!', self.bus_object_name)
    end
    local fetch = object_pool.new('fetch', empty_cb, nil, false, nil, ctx)
    local ref_chip = self.accessor_ref_chip[accessor_name]
    if not ref_chip then
        span:add_event(string.format('accessor %s ref chip does not exist', accessor_name))
        span:finish()
        error(hwproxy_error.chip_not_exist_error())
    end
    local request_info = ctor_print_info(self.bus_object_name, ref_chip.name, 'realtime_write')

    ref_chip:realtime_write(accessor_name, value, fetch)
    local obj_def = object_defs[get_class_type(accessor_name)]
    local timeout = obj_def and obj_def.request_timeout
    wait_hw_access(fetch, timeout, request_info)
    span:finish()
end

-- chip自检
function work_objects:chip_test(obj)
    if not self.access_enabled then
        log:raise('The Bus access(%s) has been closed, please manually open it!', self.bus_object_name)
    end
    local ref_chip_name = self:get_ref_chip_name(obj)
    local fetch = object_pool.new('fetch', empty_cb, nil, false)
    local request_info = ctor_print_info(self.bus_object_name, ref_chip_name, 'chip_test')

    self.chips[ref_chip_name]:chip_test(fetch)
    return wait_hw_access(fetch, nil, request_info)
end

-- 暂时停止对特定器件的硬件扫描
function work_objects:stop_chip_scanners(obj, disable_duration)
    if not self.access_enabled then
        log:warn('The current link access status is disabled. Setting the chip access status fails.')
        return
    end
    local chip_name = self:get_chip_name(obj)
    -- 设置可访问状态为不可访问,暂时停止硬件扫描
    self.chips[chip_name].accessible_status = false
    self.chips[chip_name]:stop_scanners(disable_duration)
end

-- 重新开启对特定器件的硬件扫描
function work_objects:restart_chip_scanners(obj)
    if not self.access_enabled then
        log:warn('The current link access status is disabled. Setting the chip access status fails.')
        return
    end
    local chip_name = self:get_chip_name(obj)
    -- 设置可访问状态为可访问,重新打开硬件扫描
    self.chips[chip_name].accessible_status = true
    self.chips[chip_name]:start_scanners()
end

function work_objects:stop_bus_access(disable_duration)
    self.access_enabled = false
    for _, chip_obj in pairs(self.chips) do
        chip_obj.accessible_status = false
        chip_obj:stop_scanners(disable_duration)
    end
    log:notice(
        'The bus (%s) access has been closed and the access status is [Disabled], duration: %d',
        self.bus_object_name,
        disable_duration
    )
end

function work_objects:restart_bus_access()
    for _, chip_obj in pairs(self.chips) do
        chip_obj.accessible_status = true
        chip_obj:start_scanners()
    end
    self.access_enabled = true
    log:notice('The bus (%s) access has been opened and the access status is [Enabled]', self.bus_object_name)
end

function work_objects:update_scan_enabled(scanner_name, scan_enabled)
    local ref_chip = self.scanner_ref_chip[scanner_name]
    if not ref_chip then
        error(hwproxy_error.chip_not_exist_error())
    end
    local scanner_obj = ref_chip.scanners[scanner_name]
    scanner_obj:update_scan_enabled(scanner_name, scan_enabled)
end

function work_objects:update_scanner_shm_value(scanner_name, value_name)
    local ref_chip = self.scanner_ref_chip[scanner_name]
    if ref_chip then
        local scanner_obj = ref_chip.scanners[scanner_name]
        for _, resource in pairs(scanner_obj.resources) do
            if resource.name == scanner_name then
                resource.tree_obj:update_shm_property(value_name)
            end
        end
    end
end

function work_objects:update_drv_write_delay(chip_name, value)
    self.chips[chip_name].driver.drv_write_delay = value
end

function work_objects:plugin_request(obj, ctx, plugin_name, cmd, params, control_params)
    local timeout = ctx.Timeout and tonumber(ctx.Timeout)
    local plugin = self.plugins[plugin_name]
    if not plugin then
        local m = require('hwproxy.plugins.' .. plugin_name)
        plugin = m.new(self)
        self.plugins[plugin_name] = plugin
    end

    if not plugin:has_cmd(cmd) then
        error(string.format('unknown plugin cmd %s.%s', plugin_name, cmd))
    end

    local fetch = {}
    local chip_name = self:get_chip_name(obj)
    local chip_obj = self.chips[chip_name]
    chip_obj:plugin_request(fetch, function()
        if #params == 0 then
            return skynet.packstring(plugin:run_cmd(chip_obj, cmd))
        end
        return skynet.packstring(plugin:run_cmd(chip_obj, cmd, skynet.unpack(params)))
    end, control_params, ctx)
    local request_info = ctor_print_info(self.bus_object_name, chip_name, 'plugin_request')
    return wait_hw_access(fetch, timeout, request_info)
end

function work_objects:mock_scanner_failure(scanner_name, disable_duration)
    local ref_chip = self.scanner_ref_chip[scanner_name]
    if not ref_chip then
        error(hwproxy_error.chip_not_exist_error())
    end
    return ref_chip.scanners[scanner_name]:mock_scanner_failure(disable_duration)
end

function work_objects:on_reboot_action()
    -- 停止所有的scanner扫描任务
    for _, chip_obj in pairs(self.chips) do
        for _, sc in pairs(chip_obj.scanners) do
            sc:stop()
        end
        -- 重启时停止总线下一级器件,然后递归停止所有器件
        if not chip_obj.l_chip then
            chip_obj:stop(true)
        end
    end
end

function work_objects:dump_topology()
    local bus_topo = { self.bus_object_name }
    local log_chips = {}
    local collected_chips = {}
    for _, chip in pairs(self.chips) do
        if chip.channel_id == -1 and not collected_chips[chip.name] then
            table.insert(log_chips, chip)
            collected_chips[chip.name] = true
        end
    end
    for index, chip in ipairs(log_chips) do
        table.insert(bus_topo, chip:dump_topology('', index == #log_chips and true or false))
    end
    return table.concat(bus_topo, '\n') .. '\n'
end

function work_objects:dump_aggregate_info()
    local collect_dfx = {}
    local collected_chips = {}
    for _, chip in pairs(self.chips) do
        if not collected_chips[chip.name] then
            collect_dfx[#collect_dfx + 1] = chip:dump_aggregate_info()
            collected_chips[chip.name] = true
        end
    end
    return #collect_dfx ~= 0 and t_concat(collect_dfx) or nil
end

function work_objects:dump_scanners_info()
    local collect_scanners = {}
    local collected_chips = {}
    for _, chip in pairs(self.chips) do
        if not collected_chips[chip.name] then
            collect_scanners[#collect_scanners + 1] = chip:dump_scanners_info()
            collected_chips[chip.name] = true
        end
    end
    return #collect_scanners ~= 0 and collect_scanners or nil
end

function work_objects:dump_chip_access_info(bus_name)
    local collected_chips = {}
    local collected_chips_info = {}
    for _, chip in pairs(self.chips) do
        if not collected_chips[chip.name] then
            collected_chips_info[#collected_chips_info + 1] = chip:dump_chip_access_info()
            collected_chips[chip.name] = true
        end
    end
    return #collected_chips_info ~= 0 and collected_chips_info or nil
end

function work_objects:set_health_status(obj, value)
    local chip_name = self:get_chip_name(obj)
    local chip_obj = self.chips[chip_name]
    chip_obj:set_health_status(value)
end

return work_objects