-- 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 object_pool = require('object_pool')

local t_insert = table.insert
local object_pool_recycle = object_pool.recycle
local add_table_node = utils.add_table_node
local get_table_node = utils.get_table_node
local remove_table_node = utils.remove_table_node

local EXTEND_READ_OFFSET <const> = 0xffffffff

local cache = {}
cache.__index = cache

local function update_type_indexes(type_table, inserted_at)
    if type(type_table) ~= 'table' then
        return
    end
    for type_key, index in pairs(type_table) do
        if index >= inserted_at then
            type_table[type_key] = index + 1
        end
    end
end

local function update_table_node_indexes(index_table, inserted_at)
    if type(index_table) ~= 'table' then
        return
    end
    for _, length_table in pairs(index_table) do
        for _, type_table in pairs(length_table) do
            update_type_indexes(type_table, inserted_at)
        end
    end
end

function cache.new(chip)
    return setmetatable({
        chip = chip,

        -- 缓存读请求
        read_queue = nil,
        read_queue_index = nil,

        -- 缓存写请求
        write_queue = nil,

        -- 缓存插件请求
        plugin_queue = nil,

        -- 缓存cpld升级请求
        cpld_upg_queue = nil,

        -- 缓存子通道需要更新的 chip
        child_queue = nil,
        child_queue_index = nil,

        queue_len = { read = 0, write = 0, plugin = 0, cpld_upg = 0 },
        queue_over_flag = { read = false, write = false, plugin = false, cpld_upg = false },
    }, cache)
end

function cache:set_parent(parent)
    self.parent = parent
end

function cache:clean()
    if self.parent then
        self.parent:delete_channel_chip(self.chip.channel_id, self.chip)
    end
end

function cache:read(args, head_insertion)
    local read_queue = self.read_queue
    if not read_queue then
        read_queue = {}
        self.read_queue = read_queue
        self.read_queue_index = {}
    end

    self:notify_parent(head_insertion)

    args.fetch.unexecuted = true
    local queue_len = self.queue_len
    -- RPC: WriteRead时,不需要合并fetch
    if args.offset == EXTEND_READ_OFFSET or args.protocol_flag then
        args.fetches = { args.fetch }
        args.real_masks = { args.real_mask }
        if head_insertion then
            t_insert(read_queue, 1, args)
            -- 当头部插入时,更新所有现有索引
            update_table_node_indexes(self.read_queue_index, 1)
        else
            t_insert(read_queue, args)
        end

        queue_len['read'] = queue_len['read'] + 1
        return
    end

    local read_queue_index, args_offset, args_length, args_type =
        self.read_queue_index, args.offset, args.length, args.type
    local index = get_table_node(read_queue_index, args_offset, args_length, args_type)
    -- 重复请求,合并fetch
    if index then
        if read_queue[index] ~= args then
            local queue = read_queue[index]
            local fetches, real_masks = queue.fetches, queue.real_masks
            fetches[#fetches + 1] = args.fetch
            real_masks[#real_masks + 1] = args.real_mask
            object_pool_recycle('read_args', args)
            queue_len['read'] = queue_len['read'] + 1
        end
        return
    end

    -- 添加新的请求缓存
    args.fetches = { args.fetch }
    args.real_masks = { args.real_mask }
    if head_insertion then
        t_insert(read_queue, 1, args)
        -- 当头部插入时,更新所有现有索引
        update_table_node_indexes(read_queue_index, 1)
        add_table_node(read_queue_index, 1, args_offset, args_length, args_type) -- 明确设置头部索引为1
    else
        t_insert(read_queue, args)
        add_table_node(read_queue_index, #read_queue, args_offset, args_length, args_type)
    end
    queue_len['read'] = queue_len['read'] + 1
end

function cache:write(args)
    local write_queue = self.write_queue
    if not self.write_queue then
        write_queue = {}
        self.write_queue = write_queue
    end

    args.fetch.unexecuted = true
    write_queue[#write_queue + 1] = args
    local queue_len = self.queue_len
    queue_len['write'] = queue_len['write'] + 1
    self:notify_parent()
end

function cache:plugin_request(args, head_insertion)
    local plugin_queue = self.plugin_queue
    if not plugin_queue then
        plugin_queue = {}
        self.plugin_queue = plugin_queue
    end

    for _, fetch in ipairs(args.fetches or {}) do
        fetch.unexecuted = true
    end

    if head_insertion then
        t_insert(plugin_queue, 1, args)
    else
        t_insert(plugin_queue, args)
    end
    local queue_len = self.queue_len
    queue_len['plugin'] = queue_len['plugin'] + 1
    self:notify_parent(head_insertion)
end

function cache:cpld_upg_request(args)
    local cpld_upg_queue = self.cpld_upg_queue
    if not cpld_upg_queue then
        cpld_upg_queue = {}
        self.cpld_upg_queue = cpld_upg_queue
    end

    args.fetch.unexecuted = true
    cpld_upg_queue[#cpld_upg_queue + 1] = args
    local queue_len = self.queue_len
    queue_len['cpld_upg'] = queue_len['cpld_upg'] + 1
    self:notify_parent()
end

function cache:notify_parent(head_insertion)
    local parent = self.parent
    if not parent then
        return
    end

    local chip = self.chip
    local channel_id = chip.channel_id
    if channel_id == -1 then
        return
    end

    parent:add_channel_chip(channel_id, chip, head_insertion)
    parent:notify_parent(head_insertion)
end

function cache:add_channel_chip(channel_id, chip, head_insertion)
    if not self.child_queue then
        self.child_queue = { [channel_id] = { chip } }
        self.child_queue_index = {}
    elseif not get_table_node(self.child_queue_index, channel_id, chip.name) then
        local child_queue = self.child_queue[channel_id]
        if not child_queue then
            self.child_queue[channel_id] = { chip }
        else
            if head_insertion then
                t_insert(child_queue, 1, chip)
            else
                t_insert(child_queue, chip)
            end
        end
    else
        return
    end

    add_table_node(self.child_queue_index, chip, channel_id, chip.name)

    local parent = self.parent
    if parent then
        parent:notify_parent(head_insertion)
    end
end

local function find_chip(chips, chip)
    for i, c in ipairs(chips) do
        if c == chip then
            return i
        end
    end
    return nil
end

function cache:delete_channel_chip(channel_id, chip)
    local child_queue = self.child_queue
    if not child_queue or not get_table_node(self.child_queue_index, channel_id, chip.name) then
        return
    end

    remove_table_node(self.child_queue_index, channel_id, chip.name)
    local chips = child_queue[channel_id]
    local idx = find_chip(chips, chip)
    if idx then
        chips[idx] = nil
    end
end

local function process_write_queue(write_queue, cb)
    for _, obj in ipairs(write_queue) do
        cb(obj)
    end
end

function cache:process_write(cb)
    if not self.write_queue then
        return
    end

    local write_queue = self.write_queue
    self.write_queue = nil
    self.queue_len['write'] = 0
    self.queue_over_flag['write'] = false

    local ok, err = pcall(process_write_queue, write_queue, cb)
    if not ok then
        self:flush_one_queue(write_queue, err)
    end
end

local function process_read_queue(read_queue, cb)
    for _, obj in ipairs(read_queue) do
        cb(obj)
    end
end

function cache:process_read(cb)
    if not self.read_queue then
        return
    end

    local read_queue = self.read_queue
    self.read_queue = nil
    self.read_queue_index = nil
    self.queue_len['read'] = 0
    self.queue_over_flag['read'] = false

    local ok, err = pcall(process_read_queue, read_queue, cb)
    if not ok then
        self:flush_one_queue(read_queue, err)
    end
end

local function process_plugin_queue(plugin_queue, cb)
    for _, obj in ipairs(plugin_queue) do
        cb(obj)
    end
end

function cache:process_plugin(cb)
    if not self.plugin_queue then
        return
    end

    local plugin_queue = self.plugin_queue
    self.plugin_queue = nil
    self.queue_len['plugin'] = 0
    self.queue_over_flag['plugin'] = false

    local ok, err = pcall(process_plugin_queue, plugin_queue, cb)
    if not ok then
        self:flush_one_queue(plugin_queue, err)
    end
end

local function process_cpld_upg_queue(cpld_upg_queue, cb)
    for _, obj in ipairs(cpld_upg_queue) do
        cb(obj)
    end
end

function cache:process_cpld_upg(cb)
    if not self.cpld_upg_queue then
        return
    end
    local cpld_upg_queue = self.cpld_upg_queue
    self.cpld_upg_queue = nil
    self.queue_len['cpld_upg'] = 0
    self.queue_over_flag['cpld_upg'] = false

    local ok, err = pcall(process_cpld_upg_queue, cpld_upg_queue, cb)
    if not ok then
        self:flush_one_queue(cpld_upg_queue, err)
    end
end

function cache:process_child(cb)
    local child_queue = self.child_queue
    if not child_queue then
        return
    end

    self.child_queue = nil
    self.child_queue_index = nil
    for _, chips in pairs(child_queue) do
        cb(chips)
    end
end

function cache:flush_one_queue(queue, err, stop)
    local func = function(fetch)
        -- 对于部分处理成功的,无须更新
        if fetch.unexecuted ~= true then
            return
        end

        fetch.result = false
        fetch.error = err
        fetch.unexecuted = false

        local access_obj = fetch.access_obj
        if access_obj and not stop then
            access_obj:update_resource(fetch)
        end

        fetch.cb()

        local run_again = fetch.run_again
        if run_again and not stop then
            run_again()
        end
    end

    for _, args in ipairs(queue) do
        local fetches = args.fetches
        if fetches then
            for _, fetch in pairs(fetches) do
                func(fetch)
            end
        else
            func(args.fetch)
        end
    end
end

local queue_list = { -- cb回调存放位置,后续要整改为统一的
    { 'read_queue', 'read', 'read_queue_index' }, -- fetches
    { 'write_queue', 'write' }, -- fetch
    { 'plugin_queue', 'plugin' }, -- fetches
    { 'cpld_upg_queue', 'cpld_upg' }, -- fetch
}

-- 刷新并处理所有队列中的请求(带错误通知)
--
-- 功能说明:
-- 1. 遍历处理所有类型的请求队列(读/写/插件/CPLD升级)
-- 2. 对每个队列调用flush_one_queue进行错误处理
-- 3. 重置各队列状态(长度计数器清零,完成标志设为false)
-- 4. 释放所有队列和索引表的引用
--
-- 特殊处理:
-- 1. 对读队列会额外清理read_queue_index索引表
-- 2. 会触发每个请求的错误回调(通过flush_one_queue)
-- 3. 错误信息会传递到每个请求的fetch对象
--
-- 与clear_queue的区别:
-- 1. 会执行请求的错误处理流程(调用回调函数)
-- 2. 会将错误信息传播给所有请求方
-- 3. 通常用于异常情况下的队列清理
--
-- @param err 错误信息对象,将传递给所有待处理请求
function cache:flush_queue(err)
    local queue_len = self.queue_len
    local queue_over_flag = self.queue_over_flag
    for _, v in ipairs(queue_list) do
        if self[v[1]] then
            self:flush_one_queue(self[v[1]], err, false)
            queue_len[v[2]] = 0
            queue_over_flag[v[2]] = false
            self[v[1]] = nil
            if v[3] then
                self[v[3]] = nil
            end
        end
    end
end

-- 清空所有队列中的待处理请求
--
-- 功能说明:
-- 1. 清空四类主要队列(读/写/插件/CPLD升级)中的所有待处理请求
-- 2. 重置各队列长度计数器(queue_len)为0
-- 3. 将队列完成标志(queue_over_flag)设为false
-- 4. 释放队列表和索引表的引用
--
-- 注意事项:
-- 1. 只能清除尚未被取出的请求,对已开始处理的请求无效
-- 2. 读请求会同时清除用于合并优化的read_queue_index索引表
-- 3. 该方法会立即释放内存,但不会触发任何回调
-- 4. 通常在BMC重启停止器件时,用于强制清理残留请求
function cache:clear_queue(err)
    local queue_len = self.queue_len
    local queue_over_flag = self.queue_over_flag
    for _, v in ipairs(queue_list) do
        if self[v[1]] then
            self:flush_one_queue(self[v[1]], err, true)
            queue_len[v[2]] = 0
            queue_over_flag[v[2]] = false
            self[v[1]] = nil
            if v[3] then
                self[v[3]] = nil
            end
        end
    end
end

return cache