-- 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 lu = require('luaunit')
local cache = require('cache')
local log = require('mc.logging')
local utils = require('mc.utils')

TestCache = {}

local old_log_raise = log.raise
function TestCache:setUp()
    log.raise = function() end
end

function TestCache:tearDown()
    log.raise = old_log_raise
end

function TestCache:test_flush_queue()
    local cache_obj = cache.new({})
    local count = 0
    local args1 = {
        fetch = {
            cb = function()
                count = count + 10
            end,
            run_again = function() end,
        },
        offset = 0xffffffff,
    }
    local args2 = {
        fetch = {
            cb = function()
                count = count + 1
            end,
        },
    }
    local args3 = {
        fetch = {
            cb = function()
                count = count + 3
            end,
        },
    }
    local args4 = {
        fetches = {
            {
                cb = function()
                    count = count + 100
                end,
            },
        },
    }

    cache_obj:read(args1)
    cache_obj:write(args2)
    cache_obj:write(args3)
    cache_obj:write(args3) -- 再次写入,cb不会重复调用(args3相同)
    cache_obj:plugin_request(args4)

    lu.assertEquals(cache_obj.queue_len, { cpld_upg = 0, plugin = 1, read = 1, write = 3 })
    lu.assertEquals(cache_obj.queue_over_flag, { cpld_upg = false, plugin = false, read = false, write = false })

    cache_obj:process_plugin(function() end)

    cache_obj:flush_queue('err')

    lu.assertEquals(cache_obj.queue_len, { cpld_upg = 0, plugin = 0, read = 0, write = 0 })
    lu.assertIsNil(cache_obj.read_queue)
    lu.assertIsNil(cache_obj.write_queue)
    lu.assertIsNil(cache_obj.plugin_queue)
    lu.assertEquals(count, 14) -- = 10 + 1 + 3 (最后的3和100不会加)
end

function TestCache:test_read_normal()
    local cache_obj = cache.new({ channel_id = 1 })
    local count = 0

    -- 普通读请求
    local args1 = {
        fetch = {
            cb = function()
                count = count + 1
            end,
            unexecuted = false,
        },
        offset = 0x1,
        length = 4,
        type = 'type1',
    }

    cache_obj:read(args1, false)
    lu.assertEquals(cache_obj.queue_len.read, 1)
    lu.assertEquals(#cache_obj.read_queue, 1)

    -- 验证索引是否正确建立
    local index = utils.get_table_node(cache_obj.read_queue_index, 0x1, 4, 'type1')
    lu.assertEquals(index, 1)
end

function TestCache:test_read_head_insertion()
    local cache_obj = cache.new({ channel_id = 1 })
    local count = 0

    -- 先插入普通请求
    local args1 = {
        fetch = {
            cb = function()
                count = count + 1
            end,
        },
        offset = 0x1,
        length = 4,
        type = 'type1',
    }
    cache_obj:read(args1, false)

    -- 头部插入高优先级请求
    local args2 = {
        fetch = {
            cb = function()
                count = count + 2
            end,
        },
        offset = 0x2,
        length = 4,
        type = 'type1',
    }
    cache_obj:read(args2, true)

    lu.assertEquals(cache_obj.queue_len.read, 2)
    lu.assertEquals(cache_obj.read_queue[1].fetch.cb, args2.fetch.cb) -- 验证头部插入
    lu.assertEquals(cache_obj.read_queue[2].fetch.cb, args1.fetch.cb)

    -- 验证索引更新正确性
    local index1 = utils.get_table_node(cache_obj.read_queue_index, 0x1, 4, 'type1')
    local index2 = utils.get_table_node(cache_obj.read_queue_index, 0x2, 4, 'type1')
    lu.assertEquals(index1, 2) -- 原索引应+1
    lu.assertEquals(index2, 1) -- 新索引在头部
end

function TestCache:test_read_duplicate_merge()
    local cache_obj = cache.new({ channel_id = 1 })
    local count = 0

    -- 初始请求
    local args1 = {
        fetch = {
            cb = function()
                count = count + 1
            end,
        },
        offset = 0x1,
        length = 4,
        type = 'type1',
    }
    cache_obj:read(args1, false)

    -- 相同参数的重复请求
    local args2 = {
        fetch = {
            cb = function()
                count = count + 2
            end,
        },
        offset = 0x1,
        length = 4,
        type = 'type1',
    }
    cache_obj:read(args2, false)

    lu.assertEquals(cache_obj.queue_len.read, 2) -- 长度计数增加
    lu.assertEquals(#cache_obj.read_queue, 1) -- 但队列长度不变(已合并)
    lu.assertEquals(#cache_obj.read_queue[1].fetches, 2) -- 验证fetch合并
end

function TestCache:test_read_request_merging()
    local cache_obj = cache.new({
        channel_id = 1,
        name = 'test_chip',
    })

    local call_count = 0
    local callback = function()
        call_count = call_count + 1
    end

    -- 定义相同参数的多个请求
    local base_args = {
        offset = 0x1234,
        length = 4,
        type = 'test_type',
        fetch = {
            cb = callback,
            unexecuted = true,
        },
    }

    -- 创建5个相同参数的请求(应合并)
    local requests = {}
    for i = 1, 5 do
        requests[i] = {
            offset = base_args.offset,
            length = base_args.length,
            type = base_args.type,
            fetch = {
                cb = base_args.fetch.cb,
                unexecuted = true,
            },
        }
        cache_obj:read(requests[i], false)
    end

    -- 验证队列状态
    lu.assertEquals(cache_obj.queue_len.read, 5) -- 5次调用计数
    lu.assertEquals(#cache_obj.read_queue, 1) -- 只合并为1个队列项
    lu.assertEquals(#cache_obj.read_queue[1].fetches, 5) -- 包含5个fetch

    -- 验证索引表
    local index = utils.get_table_node(cache_obj.read_queue_index, base_args.offset, base_args.length, base_args.type)
    lu.assertEquals(index, 1) -- 索引应指向第一个位置

    -- 处理队列
    cache_obj:process_read(function(args)
        for _, fetch in ipairs(args.fetches) do
            fetch.cb()
        end
    end)

    -- 验证回调执行次数
    lu.assertEquals(call_count, 5) -- 5次回调都应执行
end

function TestCache:test_mixed_read_requests()
    local cache_obj = cache.new({
        channel_id = 1,
        name = 'test_chip',
    })

    local call_counts = {
        normal = 0,
        special = 0,
        rpc = 0,
    }

    -- 1. 第一个普通请求
    local normal_args1 = {
        fetch = {
            cb = function()
                call_counts.normal = call_counts.normal + 1
            end,
        },
        offset = 0x1,
        length = 4,
        type = 'normal',
    }

    -- 2. 特殊请求(EXTEND_READ_OFFSET)
    local special_args = {
        fetch = {
            cb = function()
                call_counts.special = call_counts.special + 1
            end,
        },
        offset = 0xffffffff, -- 特殊标记
    }

    -- 3. RPC协议请求
    local rpc_args = {
        fetch = {
            cb = function()
                call_counts.rpc = call_counts.rpc + 1
            end,
        },
        offset = 0x2,
        protocol_flag = true, -- RPC标记
    }

    -- 4. 第二个普通请求(不同参数,避免合并)
    local normal_args2 = {
        fetch = {
            cb = function()
                call_counts.normal = call_counts.normal + 1
            end,
        },
        offset = 0x3, -- 不同的offset
        length = 4,
        type = 'normal',
    }

    -- 执行顺序:普通1 → 特殊 → RPC → 普通2
    cache_obj:read(normal_args1, false) -- 普通1
    cache_obj:read(special_args, true) -- 头部插入特殊
    cache_obj:read(rpc_args, false) -- RPC
    cache_obj:read(normal_args2, false) -- 普通2

    -- 验证队列状态(现在应该全部独立)
    lu.assertEquals(cache_obj.queue_len.read, 4) -- 4个独立请求
    lu.assertEquals(#cache_obj.read_queue, 4) -- 实际4个条目

    -- 验证队列顺序 (特殊请求应在头部)
    lu.assertEquals(cache_obj.read_queue[1].offset, 0xffffffff) -- 特殊
    lu.assertEquals(cache_obj.read_queue[2].offset, 0x1) -- 普通1
    lu.assertIsTrue(cache_obj.read_queue[3].protocol_flag) -- RPC
    lu.assertEquals(cache_obj.read_queue[4].offset, 0x3) -- 普通2

    -- 验证索引表
    lu.assertEquals(utils.get_table_node(cache_obj.read_queue_index, 0x1, 4, 'normal'), 2)
    lu.assertEquals(utils.get_table_node(cache_obj.read_queue_index, 0x3, 4, 'normal'), 4)
    lu.assertIsNil(utils.get_table_node(cache_obj.read_queue_index, 0xffffffff, nil, nil))
    lu.assertIsNil(utils.get_table_node(cache_obj.read_queue_index, 0x2, nil, nil))

    -- 处理队列
    cache_obj:process_read(function(args)
        if args.fetches then
            for _, f in ipairs(args.fetches) do
                f.cb()
            end
        else
            args.fetch.cb()
        end
    end)

    -- 验证回调次数
    lu.assertEquals(call_counts.normal, 2) -- 两个独立普通请求
    lu.assertEquals(call_counts.special, 1)
    lu.assertEquals(call_counts.rpc, 1)
end

function TestCache:test_read_rpc_special()
    local cache_obj = cache.new({ channel_id = 1 })
    local count = 0

    -- 特殊请求(EXTEND_READ_OFFSET)
    local args1 = {
        fetch = {
            cb = function()
                count = count + 1
            end,
        },
        offset = 0xffffffff,
        protocol_flag = true,
    }
    cache_obj:read(args1, true)

    lu.assertEquals(cache_obj.queue_len.read, 1)
    lu.assertEquals(cache_obj.read_queue[1].offset, 0xffffffff)
    lu.assertEquals(cache_obj.read_queue_index, {}) -- 特殊请求不应建立索引
end

function TestCache:test_read_with_parent()
    local parent = cache.new({
        channel_id = 0,
        name = 'parent_chip',
    })

    -- 初始化parent的队列结构
    parent.child_queue = {}
    parent.child_queue_index = {}

    -- 创建两个不同的chip对象,确保能被添加到队列中
    local child1 = cache.new({
        channel_id = 1,
        name = 'child_chip_1', -- 唯一name
    })
    local child2 = cache.new({
        channel_id = 1,
        name = 'child_chip_2', -- 另一个唯一name
    })
    child1:set_parent(parent)
    child2:set_parent(parent)

    local args = {
        fetch = { cb = function() end },
        offset = 0x1,
        length = 4,
        type = 'type1',
    }

    -- 第一个读请求
    child1:read(args, true)
    lu.assertEquals(#parent.child_queue[1], 1)

    -- 第二个读请求使用不同的chip
    child2:read(args, false)
    lu.assertEquals(#parent.child_queue[1], 2)

    -- 验证索引
    lu.assertNotNil(parent.child_queue_index[1]['child_chip_1'])
    lu.assertNotNil(parent.child_queue_index[1]['child_chip_2'])
end