-- 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 log = require('mc.logging')
local utils = require('mc.utils')
local class = require('mc.class')
local scan_context = require('scan_context')
local c_tasks = require('mc.orm.tasks')
local skynet = require('skynet')
local coroutine = require('skynet.coroutine')

local skynet_id = skynet.self()
local skynet_send = skynet.send
local skynet_wait = skynet.wait
local skynet_sleep = skynet.sleep
local skynet_wakeup = skynet.wakeup
local math_ceil = math.ceil
local c_running = coroutine.running

local scan = class()
local proto_id = 1
function scan:ctor(bus_object)
    self.bus = bus_object
    self.chips = {}
    setmetatable(self.chips, { __mode = 'kv' })
end

function scan:init() end

-- 在当前扫描拓扑中增加chip
function scan:add_chip(chip_obj)
    if self.chips[chip_obj.name] then
        log:mcf_error('Add new chip in scan duplicated, chip_name: %s', chip_obj.name)
        return
    end
    utils.add_table_node(self.chips, chip_obj, chip_obj.name)
end

-- 在当前扫描拓扑中删除chip
function scan:delete_chip(chip_name)
    if not self.chips[chip_name] or self.chips[chip_name].ref_count ~= 0 then
        return
    end
    self.chips[chip_name]:stop()
    log:hw_stream_info('chip: %s was deleted in topology, pre_device is %s', chip_name, self.bus.name)
    utils.remove_table_node(self.chips, chip_name)
end

-- 进行一次扫描
function scan:run_once(ctx, cb)
    if not self.bus then
        log:mcf_error('Bus not exist, start scan failed')
        return false
    end

    local stream = self.bus.stream
    local bus_unlock = stream and stream.bus_unlock
    local bus_lock = stream and stream.bus_lock
    for _, chip_obj in pairs(self.chips) do
        if bus_lock then
            bus_lock(stream)
        end
        local ok, err = pcall(cb, chip_obj, ctx)
        if bus_unlock then
            bus_unlock(stream)
        end
        if not ok then
            log:hw_stream_error('chip: %s run failed error: %s', chip_obj.name, err)
        end
    end
    return true
end

local HIGH_PRIO_CHECK_INTERVAL <const> = 50

function scan:register_protocol_and_dispatch(pname)
    local PTYPE_SWITH = 66 + proto_id
    proto_id = proto_id + 1
    skynet.register_protocol({ name = pname, id = PTYPE_SWITH, pack = skynet.pack, unpack = skynet.unpack })

    self.wait_co = nil
    skynet.dispatch(pname, function(_, _)
        local wait_co = self.wait_co
        if wait_co then
            skynet_wakeup(wait_co)
        end
    end)
end

local function process_low_priority_task(self, ctx)
    ctx:begin_run()

    self:run_once(ctx, function(chip_obj)
        return chip_obj:run(ctx)
    end)

    local t = ctx:end_run()
    return math_ceil(t / 10) * 10
end

local function process_secondary_priority_task(self, ctx)
    if not self.has_secondary_task then
        return false
    end
    ctx:begin_run()

    self:run_once(ctx, function(chip_obj)
        return chip_obj:secondary_run(ctx)
    end)

    ctx:end_run()
    self.has_secondary_task = false
end

local function process_high_priority_task_once(self, ctx)
    if not self.has_high_task then
        return false
    end

    ctx:begin_run()
    self:run_once(ctx, function(chip_obj)
        return chip_obj:high_run(ctx)
    end)
    ctx:end_run()
    self.has_high_task = false
    return true
end

local function process_high_priority_task(self, ctx)
    if ctx.running_co or not process_high_priority_task_once(self, ctx) then
        return
    end

    -- 对某些连续读取大量数据的场景做如下优化:
    -- 1、睡眠 10 毫秒后检查是否有新的高优先级任务,如果没有增加失败次数统计
    -- 2、失败次数累计超过 5 次直接中断等待
    -- 3、不管成功失败最多轮询等待 10 次,也就是 100 毫秒
    local failed_count = 0
    for _ = 1, 10 do
        ctx.running_co = c_running()
        skynet_sleep(1)
        ctx.running_co = nil
        if not process_high_priority_task_once(self, ctx) then
            if failed_count > 5 then
                break
            end
            failed_count = failed_count + 1
        end
    end
end

scan.process_low_priority_task = process_low_priority_task
scan.process_secondary_priority_task = process_secondary_priority_task
scan.process_high_priority_task_once = process_high_priority_task_once
scan.process_high_priority_task = process_high_priority_task

function scan:set_step_cb(low_ctx, secondary_ctx, high_ctx, pname)
    local function flush_message()
        skynet_send(skynet_id, pname, 1)
        self.wait_co = c_running()
        skynet_wait()
        self.wait_co = nil
    end

    local stream = self.bus.stream
    local bus_unlock = stream and stream.bus_unlock
    local bus_lock = stream and stream.bus_lock
    low_ctx:set_step_cb(HIGH_PRIO_CHECK_INTERVAL, function()
        if bus_unlock then
            bus_unlock(stream)
        end
        flush_message()
        process_high_priority_task(self, high_ctx)
        process_secondary_priority_task(self, secondary_ctx)
        if bus_lock then
            bus_lock(stream)
        end
    end)

    secondary_ctx:set_step_cb(HIGH_PRIO_CHECK_INTERVAL, function()
        if bus_unlock then
            bus_unlock(stream)
        end
        flush_message()
        process_high_priority_task(self, high_ctx)
        if bus_lock then
            bus_lock(stream)
        end
    end)
end

function scan:run()
    local tasks = c_tasks.get_instance()

    local low_ctx = scan_context.new(self.bus.name, self.bus.scan_interval)
    local secondary_ctx = scan_context.new(self.bus.name, 0)
    local high_ctx = scan_context.new(self.bus.name, 0)

    local PNAME = 'co_switch' .. proto_id
    self:register_protocol_and_dispatch(PNAME)

    -- 创建定时扫描任务
    tasks:new_task('scan.' .. self.bus.name):loop(function(task)
        task.timeout_ms = process_low_priority_task(self, low_ctx)
        process_high_priority_task_once(self, high_ctx)
        process_secondary_priority_task(self, secondary_ctx)
    end)

    -- 扫描任务每执行一定时间都会切出来执行高优先级任务
    self:set_step_cb(low_ctx, secondary_ctx, high_ctx, PNAME)

    -- 订阅高优先级任务通知
    self.bus:set_high_task_cb(function()
        self.has_high_task = true
        if low_ctx.is_running or high_ctx.is_running or secondary_ctx.is_running then
            -- 当正在运行高优先级任务时,等待任务结束后设置has_high_task标记,确保下一轮优先级任务有机会被唤醒
            while high_ctx.is_running do
                skynet_sleep(1)
            end
            self.has_high_task = true
            -- 如果有扫描任务正在执行,那等这轮扫描完成或 HIGH_PRIO_CHECK_INTERVAL 时间到
            return
        end

        local high_running_co = high_ctx.running_co
        if high_running_co then
            skynet_wakeup(high_running_co)
        end
    end)

    self.bus:set_secondary_task_cb(function()
        self.has_secondary_task = true
        if low_ctx.is_running or high_ctx.is_running or secondary_ctx.is_running then
            -- 当正在运行次优先级任务时,等待任务结束后设置has_secondary_task标记,确保下一轮优先级任务有机会被唤醒
            while secondary_ctx.is_running do
                skynet_sleep(1)
            end
            self.has_secondary_task = true
            -- 如果有扫描任务正在执行,那等这轮扫描完成或 HIGH_PRIO_CHECK_INTERVAL 时间到
            return
        end
    end)
end

return scan