-- 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 utils = require('mc.utils')
local log = require('mc.logging')
local skynet = require('skynet')
local mc_context = require('mc.context')
local trace = require('telemetry.trace')

local time_ms = utils.time_ms
local skynet_sleep = skynet.sleep
local get_context = mc_context.get_context
local with_context = mc_context.with_context

local context = {}
context.__index = context

local ACCESS_SUCCESS = 0
local ACCESS_FAILED = 1

function context.new(bus_name, interval)
    return setmetatable({
        stack = {},
        bus_name = bus_name,
        interval = interval,
        is_running = false,
    }, context)
end

function context:begin_run()
    self.start_time = time_ms()
    self.is_running = true
end

function context:set_step_cb(interval, cb)
    self.step_interval = interval
    self.step_cb = cb
end

function context:end_run()
    self.is_running = false
    local interval = self.interval
    if interval == 0 then
        return 0
    end

    local st = self.start_time
    local ct = time_ms()
    local dt = (ct > st) and (ct - st) or 0
    if dt > interval then
        return 0
    end
    return interval - dt
end

function context:push(chip)
    self.stack[#self.stack + 1] = chip
end

function context:pop()
    local n = #self.stack
    if n == 0 then
        return
    end

    local chip = self.stack[n]
    self.stack[n] = nil
    chip:close_channel()
end

function context:last_opened_channel()
    local stack = self.stack
    for i = #stack, 1, -1 do
        local chip = stack[i]
        if not chip.l_chip then
            return i
        end
    end

    return 1
end

-- 当前9545等经常性出现切换失败的情况,做三次重试
-- 从当前 chip 开始向上遍历打开整条通道
-- 必须从下向上找到第一个已经打开的通道,再往下逐层打开
function context:open_channels()
    local span = trace.start_span(
        'hwproxy.scan_context.open_channels',
        trace.get_status() and { ['service.name'] = 'bmc.kepler.hwproxy' } or nil
    )
    local ok, err, err_info, chip
    local retries = 1
    local stack = self.stack
    while retries <= 3 do
        ok, err = pcall(function()
            for i = self:last_opened_channel() + 1, #stack do
                chip = stack[i]
                chip.l_chip:open_channel(chip.channel_id)
            end
        end)

        if ok then
            -- 通道打开成功,除末端器件外,其余器件状态置为访问成功
            for i = self:last_opened_channel(), #stack - 1 do
                chip = stack[i]
                chip:update_access_status(ACCESS_SUCCESS)
            end
            span:finish()
            return
        end

        -- 访问失败,器件状态置为本级器件不可访问
        chip.l_chip:update_access_status(ACCESS_FAILED)
        err_info = string.format('bus: %s, %s[times:%d]', self.bus_name, err, retries)
        log:hw_stream_error(err_info)
        retries = retries + 1
        skynet_sleep(1)
    end
    span:set_status('error', err_info)
    span:finish()
    error(err_info, 0)
end

function context:close_channels()
    for i = #self.stack, 1, -1 do
        local chip = self.stack[i]
        if chip then
            chip:close_channel()
        end
    end
end

function context:run_once(f, chip, obj, ...)
    local ctx
    if obj.fetch and obj.fetch.ctx then
        ctx = obj.fetch.ctx
    else
        ctx = get_context()
    end

    local ok, err = with_context(ctx, pcall, f, chip, obj, ...)
    if not ok then
        log:debug('run once failed: %s, chip_name: %s', err, self.name)
    end

    local step_cb = self.step_cb
    if not step_cb then
        return
    end

    local ct = time_ms()
    local st = self.start_time
    if ct > st and (ct - st) > self.step_interval then
        self.is_running = false
        self:close_channels()
        ok, err = pcall(step_cb)
        self.is_running = true
        if not ok then
            log:mcf_debug('run once step failed: %s, chip_name: %s', err, self.name)
        end

        -- 从较高优先级回来,通道可能被切走了,这里需要重新打开
        self:open_channels()

        -- 重新计时
        self.start_time = time_ms()
    end
end

return context