/*
 * 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.
 */

#include <chrono>
#include <cstdio>
#include <cstdlib>
#include <dlfcn.h>
#include <fstream>
#include <internal/chip/chip_base/chip.h>
#include <internal/chip/chip_base/lua_engine.h>
#include <internal/hasdef.h>
#include <mc/dict.h>
#include <memory>
#include <string>
#include <unistd.h>
#include <vector>
#include <gtest/gtest.h>

#if COMPONENT_DRIVERS_ENABLE_UNIDEV
#include <internal/chip/chip_base/lua_chip_binding.h>
#endif

#include "../test_utils/mock_bus.h"

namespace {

// 将原始字节打包为 skynet seri 格式的字符串,供 _luaseri_unpack 解包
static std::vector<uint8_t> seri_pack_string(const std::vector<uint8_t>& raw)
{
    std::vector<uint8_t> buf;
    size_t               len               = raw.size();
    constexpr uint8_t    TYPE_SHORT_STRING = 4;
    constexpr uint8_t    TYPE_LONG_STRING  = 5;
    constexpr int        MAX_COOKIE        = 32;
    if (len < MAX_COOKIE) {
        buf.push_back(static_cast<uint8_t>(TYPE_SHORT_STRING | (len << 3)));
        buf.insert(buf.end(), raw.begin(), raw.end());
    } else if (len < 0x10000) {
        buf.push_back(static_cast<uint8_t>(TYPE_LONG_STRING | (2 << 3)));
        uint16_t x = static_cast<uint16_t>(len);
        buf.insert(buf.end(), reinterpret_cast<uint8_t*>(&x), reinterpret_cast<uint8_t*>(&x) + sizeof(x));
        buf.insert(buf.end(), raw.begin(), raw.end());
    } else {
        buf.push_back(static_cast<uint8_t>(TYPE_LONG_STRING | (4 << 3)));
        uint32_t x = static_cast<uint32_t>(len);
        buf.insert(buf.end(), reinterpret_cast<uint8_t*>(&x), reinterpret_cast<uint8_t*>(&x) + sizeof(x));
        buf.insert(buf.end(), raw.begin(), raw.end());
    }
    return buf;
}

class test_bus_for_plugin : public dev::bus_base {
public:
    test_bus_for_plugin()           = default;
    ~test_bus_for_plugin() override = default;

    uint32_t read(ACCESS_DATA_S& input) override
    {
        ++m_read_call_count;
        m_last_access = input;
        input.out_buffer.clear();
        if (!m_read_payloads.empty()) {
            input.out_buffer = m_read_payloads.front();
            m_read_payloads.erase(m_read_payloads.begin());
        } else {
            for (uint32_t i = 0; i < input.length; ++i) {
                input.out_buffer.push_back(static_cast<uint8_t>(i));
            }
        }
        return m_read_result;
    }

    uint32_t write(ACCESS_DATA_S& input) override
    {
        ++m_write_call_count;
        m_last_access = input;
        return m_write_result;
    }

    uint8_t get_id() override
    {
        return m_id;
    }
    void bus_lock() override
    {
        ++m_lock_call_count;
    }
    void bus_unlock() override
    {
        ++m_unlock_call_count;
    }

    void set_id(uint8_t id)
    {
        m_id = id;
    }
    void set_read_result(int32_t result)
    {
        m_read_result = result;
    }
    void set_write_result(int32_t result)
    {
        m_write_result = result;
    }
    void add_read_payload(const std::vector<uint8_t>& payload)
    {
        m_read_payloads.push_back(payload);
    }
    void set_object_name(const std::string& name)
    {
        m_object_name = name;
    }

    ACCESS_DATA_S m_last_access{};
    int           m_read_call_count   = 0;
    int           m_write_call_count  = 0;
    int           m_lock_call_count   = 0;
    int           m_unlock_call_count = 0;

private:
    uint8_t                           m_id           = 0;
    int32_t                           m_read_result  = HAS_OK;
    int32_t                           m_write_result = HAS_OK;
    std::vector<std::vector<uint8_t>> m_read_payloads;
};

class lua_plugin_test : public ::testing::Test {
protected:
    void SetUp() override
    {
        m_bus = std::make_shared<test_bus_for_plugin>();
        m_bus->set_id(1);
        m_bus->set_object_name("plugin_test_bus");
        m_chip = std::make_shared<dev::chip_base>();

        mc::mutable_dict csr_object;
        csr_object["object_name"] = std::string("plugin_test_chip");
        csr_object["Address"]     = static_cast<uint32_t>(0x70);
        csr_object["OffsetWidth"] = static_cast<uint8_t>(1);
        csr_object["AddrWidth"]   = static_cast<uint8_t>(1);
        m_chip->init(csr_object);
        m_chip->set_left_bus(m_bus);
        m_chip->set_host_bus(m_bus);

        const char* root_dir = std::getenv("ROOT_DIR");
        if (root_dir != nullptr && root_dir[0] != '\0') {
            m_test_dir = std::string(root_dir) + "/opt/bmc/lualib";
        } else {
            char cwd[4096];
            m_test_dir = std::string(getcwd(cwd, sizeof(cwd))) + "/opt/bmc/lualib";
        }

        // 从源码树拷贝 bootstrap.lua 和 test_plugin 到构建目录
        std::string bootstrap_src;
        std::string bootstrap_dst     = m_test_dir + "/hwproxy/plugins/bootstrap.lua";
        std::string bootstrap_dst_dir = m_test_dir + "/hwproxy/plugins";
        bool        bootstrap_copied  = false;

        const char* src_root = std::getenv("MESON_SOURCE_ROOT");
        if (src_root) {
            bootstrap_src         = std::string(src_root) + "/drivers/internal/chip/chip_base/lua/bootstrap.lua";
            std::string mkdir_cmd = "mkdir -p " + bootstrap_dst_dir;
            std::system(mkdir_cmd.c_str());
            std::string cp_cmd = "cp " + bootstrap_src + " " + bootstrap_dst + " 2>/dev/null";
            std::system(cp_cmd.c_str());
            std::ifstream check(bootstrap_dst);
            if (check.good() && check.peek() != std::ifstream::traits_type::eof()) {
                bootstrap_copied = true;
            }
            check.close();
        }

        // 如果复制失败或 MESON_SOURCE_ROOT 未设置,内联创建测试用 bootstrap.lua
        if (!bootstrap_copied) {
            std::ofstream bf(bootstrap_dst);
            bf << R"lua(
if not PLUGIN_BASE_PATH then
    PLUGIN_BASE_PATH = "/opt/bmc/lualib"
end

local ROOT_PREFIX = PLUGIN_BASE_PATH:match("^(.*)/opt/bmc/lualib$") or ""
local LMC_LUALIB_PATH = ROOT_PREFIX .. "/opt/bmc/lualib/lmc"

package.path = table.concat({
    LMC_LUALIB_PATH .. "/?.lua",
    LMC_LUALIB_PATH .. "/?/init.lua",
    PLUGIN_BASE_PATH .. "/?.lua",
    PLUGIN_BASE_PATH .. "/?/init.lua",
    PLUGIN_BASE_PATH .. "/hwproxy/plugins/?.lua",
    PLUGIN_BASE_PATH .. "/hwproxy/plugins/?/init.lua",
    package.path,
}, ";")

package.cpath = table.concat({
    PLUGIN_BASE_PATH .. "/?.so",
    PLUGIN_BASE_PATH .. "/hwproxy/plugins/?.so",
    package.cpath,
}, ";")

-- mock skynet module with minimal stubs
_G.skynet = {
    sleep = function() end,
    timeout = function(t, fn) if fn then fn() end end,
}

-- mock mc.seri module for test
-- 必须设置 package.loaded,使 C++ require('mc.seri') 能返回正确的 module 表
_G.mc = _G.mc or {}
_G.mc.seri = {
    unpack = function(data)
        if not data or #data == 0 then
            return nil
        end
        -- 解析 seri 格式的字符串
        -- TYPE_SHORT_STRING = 4, 格式: type_byte | (len << 3)
        -- TYPE_LONG_STRING = 5, 格式: type_byte | (cookie << 3), 后跟长度字段
        local type_byte = string.byte(data, 1)
        local type_id = type_byte & 0x07
        local cookie = (type_byte >> 3) & 0x1F

        local raw_data = ""
        if type_id == 4 then -- TYPE_SHORT_STRING
            local len = cookie
            raw_data = string.sub(data, 2, 1 + len)
        elseif type_id == 5 then -- TYPE_LONG_STRING
            local len_size = cookie
            if len_size == 2 then
                local len = string.byte(data, 2) | (string.byte(data, 3) << 8)
                raw_data = string.sub(data, 4, 3 + len)
            elseif len_size == 4 then
                local len = string.byte(data, 2) | (string.byte(data, 3) << 8) |
                           (string.byte(data, 4) << 16) | (string.byte(data, 5) << 24)
                raw_data = string.sub(data, 6, 5 + len)
            end
        end

        -- 直接返回原始字符串(与真实 mc.seri.unpack 行为一致)
        return raw_data
    end,
    pack = function(...)
        local args = {...}
        if #args == 0 then
            return ""
        end
        -- 将所有返回值转为二进制字符串,确保 lua_tolstring() 能正确取到数据
        local result = ""
        for i = 1, #args do
            local v = args[i]
            if type(v) == "string" then
                result = result .. v
            elseif type(v) == "number" then
                result = result .. string.char(math.floor(v) % 256)
            elseif type(v) == "boolean" then
                result = result .. (v and "\1" or "\0")
            end
        end
        return result
    end,
}
package.loaded["mc.seri"] = _G.mc.seri

-- mock其他必要模块
package.loaded["skynet"] = _G.skynet

function _load_chip_plugin(plugin_name)
    local full_name = "hwproxy.plugins." .. plugin_name
    local ok, plugin = pcall(require, full_name)
    if not ok then
        package.loaded[full_name] = nil
        return nil, "failed to load plugin '" .. plugin_name .. "': " .. tostring(plugin)
    end
    return plugin
end

function _execute_chip_plugin(plugin, chip, plugin_cmd, params)
    if not plugin then
        return false, "plugin is nil"
    end
    if type(plugin.has_cmd) ~= "function" then
        return false, "plugin missing has_cmd method"
    end
    if not plugin:has_cmd(plugin_cmd) then
        return false, "plugin does not support command '" .. plugin_cmd .. "'"
    end
    if type(plugin.run_cmd) ~= "function" then
        return false, "plugin missing run_cmd method"
    end
    return plugin.run_cmd(plugin, chip, plugin_cmd, params)
end
)lua";
            bf.close();
        } else {
            // 复制成功后,修改 bootstrap.lua 将真实的 skynet/mc.seri require 替换为 mock
            // 读取 bootstrap 内容
            std::ifstream     rf(bootstrap_dst);
            std::stringstream ss;
            ss << rf.rdbuf();
            std::string bootstrap_code = ss.str();
            rf.close();

            // 替换 require('skynet') 为 mock
            {
                std::string pattern   = "local _skynet = require('skynet')";
                std::string mock_line = R"(-- mock skynet module for test (real require replaced in test environment)
_G.skynet = {
    sleep = function() end,
    timeout = function(t, fn) if fn then fn() end end,
}
package.loaded["skynet"] = _G.skynet
local _skynet = _G.skynet)";
                size_t      pos       = bootstrap_code.find(pattern);
                if (pos != std::string::npos) {
                    bootstrap_code.replace(pos, pattern.length(), mock_line);
                }
            }

            // 替换 require('mc.seri') 及后续的 _skynet.sleep 和 _skynet.timeout 覆盖
            {
                std::string pattern   = R"(local mc_seri = require('mc.seri')

function _skynet.sleep(t)
end

function _skynet.timeout(t, fn)
    if fn then
        fn()
    end
end)";
                std::string mock_code = R"(-- mock mc.seri for test
_G.mc = _G.mc or {}
_G.mc.seri = {
    unpack = function(data)
        if not data or #data == 0 then
            return nil
        end
        -- 解析 seri 格式的字符串
        -- TYPE_SHORT_STRING = 4, 格式: type_byte | (len << 3)
        -- TYPE_LONG_STRING = 5, 格式: type_byte | (cookie << 3), 后跟长度字段
        local type_byte = string.byte(data, 1)
        local type_id = type_byte & 0x07
        local cookie = (type_byte >> 3) & 0x1F

        local raw_data = ""
        if type_id == 4 then -- TYPE_SHORT_STRING
            local len = cookie
            raw_data = string.sub(data, 2, 1 + len)
        elseif type_id == 5 then -- TYPE_LONG_STRING
            local len_size = cookie
            if len_size == 2 then
                local len = string.byte(data, 2) | (string.byte(data, 3) << 8)
                raw_data = string.sub(data, 4, 3 + len)
            elseif len_size == 4 then
                local len = string.byte(data, 2) | (string.byte(data, 3) << 8) |
                           (string.byte(data, 4) << 16) | (string.byte(data, 5) << 24)
                raw_data = string.sub(data, 6, 5 + len)
            end
        end

        -- 直接返回原始字符串(与真实 mc.seri.unpack 行为一致)
        return raw_data
    end,
    pack = function(...)
        local args = {...}
        if #args == 0 then
            return ""
        end
        -- 将所有返回值转为二进制字符串,确保 lua_tolstring() 能正确取到数据
        local result = ""
        for i = 1, #args do
            local v = args[i]
            if type(v) == "string" then
                result = result .. v
            elseif type(v) == "number" then
                result = result .. string.char(math.floor(v) % 256)
            elseif type(v) == "boolean" then
                result = result .. (v and "\1" or "\0")
            end
        end
        return result
    end,
}
package.loaded["mc.seri"] = _G.mc.seri
local mc_seri = _G.mc.seri

-- mock skynet sleep/timeout (real ones replaced in test environment)
function _skynet.sleep(t)
end

function _skynet.timeout(t, fn)
    if fn then
        fn()
    end
end)";
                size_t      pos       = bootstrap_code.find(pattern);
                if (pos != std::string::npos) {
                    bootstrap_code.replace(pos, pattern.length(), mock_code);
                }
            }

            // 写回修改后的 bootstrap.lua
            std::ofstream wf(bootstrap_dst);
            wf << bootstrap_code;
            wf.close();
        }

        // 从源码树拷贝 test_plugin 到构建目录
        std::string plugin_dir = m_test_dir + "/hwproxy/plugins/test_plugin";
        std::string cmd        = "mkdir -p " + plugin_dir;
        std::system(cmd.c_str());
        std::string dst_file       = plugin_dir + "/init.lua";
        bool        plugin_created = false;

        if (src_root) {
            std::string src_file = std::string(src_root) + "/tests/drivers/internal/chip/test_plugin/init.lua";
            std::string cp_cmd   = "cp " + src_file + " " + dst_file + " 2>/dev/null";
            int         ret      = std::system(cp_cmd.c_str());
            // 检查文件是否存在且大小大于0
            std::ifstream check(dst_file);
            if (check.good() && check.peek() != std::ifstream::traits_type::eof()) {
                plugin_created = true;
            }
            check.close();
        }

        // 如果复制失败或 MESON_SOURCE_ROOT 未设置,内联创建测试插件
        if (!plugin_created) {
            std::ofstream f(dst_file);
            f << R"lua(
local class = require("mc.class")
local M = class()
M._cmds = {}
local new_count = 0

function M:ctor(app)
    new_count = new_count + 1
    self.app = app
    self.new_count = new_count
    self.initialized = false
end

function M:init()
    self.initialized = true
end

function M._cmds.read_data(chip, params)
    local data = chip:block_read(0x10, 4)
    return data
end

function M._cmds.write_data(chip, params)
    chip:block_write(0x20, params)
    return ""
end

function M._cmds.bit_read_test(chip, params)
    local data = chip:bit_read(0x10, 1, 0xFF)
    return data
end

function M._cmds.echo(chip, params)
    return params
end

function M._cmds.block_write_read_test(chip, params)
    local data = chip:block_write_read(0x10, params, 4)
    return data
end

function M._cmds.combo_test(chip, params)
    local data = chip:combo_block_write_read(0x10, params, 0x20, 4)
    return data
end

function M._cmds.write_simple(chip, params)
    local ok, err = chip:write(0x30, params)
    return ok
end

function M._cmds.write_table_block(chip, params)
    local ok, err = chip:write{offset=0x30, data=params, type=1}
    return ok
end

function M._cmds.write_table_bit(chip, params)
    local ok, err = chip:write{offset=0x10, data="\x01", type=0, mask=0xFF, length=1}
    return ok
end

function M._cmds.bit_write_test(chip, params)
    local ok, err = chip:bit_write(0x10, 1, 0xFF, "\x01")
    return ok
end

function M._cmds.read_simple(chip, params)
    local data = chip:read(0x10, 4)
    return data
end

function M._cmds.read_table_block(chip, params)
    local data = chip:read{offset=0x10, length=4, type=1}
    return data
end

function M._cmds.read_table_bit(chip, params)
    local data = chip:read{offset=0x10, length=1, type=0, mask=0xFF}
    return data
end

function M._cmds.write_fail(chip, params)
    local ok, err = chip:write(0x30, params)
    return ok
end

function M._cmds.multi_return(chip, params)
    return "hello", "world"
end

function M._cmds.pcall_read(chip, params)
    local ok, ret = pcall(chip.read, chip, {offset = 0x10, length = 4, type = 1})
    return ok, ret
end

function M._cmds.props_roundtrip(chip, params)
    if chip.name ~= 'plugin_test_chip' then
        return false, 'name: ' .. tostring(chip.name)
    end
    if type(chip.ismonitored) ~= 'boolean' then
        return false, 'ismonitored type: ' .. type(chip.ismonitored)
    end
    if chip.driver.address ~= 0x70 then
        return false, 'address: ' .. tostring(chip.driver.address)
    end
    if chip.driver.addr_width ~= 1 then
        return false, 'addr_width: ' .. tostring(chip.driver.addr_width)
    end
    if chip.driver.offset_width ~= 1 then
        return false, 'offset_width: ' .. tostring(chip.driver.offset_width)
    end
    if chip.read_retry_times ~= 0 then
        return false, 'read_retry_times initial: ' .. tostring(chip.read_retry_times)
    end
    local tmp = chip.driver.address
    chip.driver.address = chip.read_retry_times
    chip.read_retry_times = tmp
    if chip.driver.address ~= 0 then
        return false, 'address after swap: ' .. tostring(chip.driver.address)
    end
    if chip.read_retry_times ~= 0x70 then
        return false, 'read_retry_times after swap: ' .. tostring(chip.read_retry_times)
    end
    chip.driver.address = tmp
    chip.read_retry_times = 0
    chip.write = function()
        return 'overridden'
    end
    if chip.write() ~= 'overridden' then
        return false, 'write override failed'
    end
    return true
end

function M._cmds.l_chip_check(chip, params)
    if chip.l_chip == nil then
        return false, 'l_chip is nil'
    end
    if type(chip.l_chip.block_read) ~= 'function' then
        return false, 'l_chip.block_read type: ' .. type(chip.l_chip.block_read)
    end
    if chip.l_chip.name ~= 'left_chip' then
        return false, 'l_chip.name: ' .. tostring(chip.l_chip.name)
    end
    return true
end

function M._cmds.object_pool_roundtrip(chip, params)
    local object_pool = require('object_pool')

    -- power_mgmt chip_read 同款:object_pool.new('input_args', cmd, mask, type, len) + chip:read(input)
    local input = object_pool.new('input_args', 0x10, 0xffffffff, 1, 4)
    local data = chip:read(input)
    if #data ~= 4 then
        return false, 'chip:read(input_args) length mismatch: ' .. #data
    end
    object_pool.recycle('input_args', input)

    -- 池复用:recycle 后 new 应返回同一实例,且 rector 重置字段
    local reused = object_pool.new('input_args', 0x20, 0xffffffff, 1, 2)
    if reused ~= input then
        return false, 'object pool did not reuse recycled input_args'
    end
    if reused.offset ~= 0x20 or reused.length ~= 2 then
        return false, 'rector did not reset fields: ' .. tostring(reused.offset) .. '/' .. tostring(reused.length)
    end
    object_pool.recycle('input_args', reused)

    -- fetch 对象(wait_hw_access 同款):new/recycle 复用
    local fetch = object_pool.new('fetch', nil, 'result', nil, nil, 'ctx')
    if fetch.result ~= 'result' or fetch.ctx ~= 'ctx' then
        return false, 'fetch rector fields mismatch'
    end
    object_pool.recycle('fetch', fetch)

    local fetch2 = object_pool.new('fetch')
    if fetch2 ~= fetch then
        return false, 'object pool did not reuse recycled fetch'
    end
    if fetch2.result ~= nil then
        return false, 'fetch rector did not reset result'
    end
    object_pool.recycle('fetch', fetch2)

    return true
end

function M:has_cmd(cmd)
    return cmd == "constructor_app" or self._cmds[cmd] ~= nil
end

function M:run_cmd(chip, cmd, params)
    if cmd == "constructor_app" then
        if self.app == chip then
            return false, "plugin app must be independent from chip binding"
        end
        if self.app.bus_object_name ~= "plugin_test_bus" then
            return false, "plugin app bus_object_name mismatch: " .. tostring(self.app.bus_object_name)
        end
        if not self.initialized then
            return false, "plugin init was not called"
        end
        if self.new_count ~= 1 then
            return false, "plugin instance was constructed more than once"
        end
        return true
    end
    return self._cmds[cmd](chip, params)
end

return M
)lua";
            f.flush();
            f.close();
        }
    }

    void TearDown() override
    {}

    std::shared_ptr<test_bus_for_plugin> m_bus;
    std::shared_ptr<dev::chip_base>      m_chip;
    std::string                          m_test_dir;
};

// 非 UNIDEV 模式:使用原始 block_write/block_read 实现

TEST_F(lua_plugin_test, plugin_request_write_failure)
{
    std::vector<uint8_t> params = {0xAA};
    std::vector<uint8_t> out_buffer;
    std::string          error;

    m_bus->set_write_result(HAS_ERR);

    int32_t ret = m_chip->plugin_request("test_plugin", "test_cmd", params, out_buffer, error);
    EXPECT_EQ(ret, HAS_ERR);
    EXPECT_FALSE(error.empty());
}

TEST_F(lua_plugin_test, plugin_request_read_failure)
{
    std::vector<uint8_t> params = {0xAA};
    std::vector<uint8_t> out_buffer;
    std::string          error;

    m_bus->set_read_result(HAS_ERR);

    int32_t ret = m_chip->plugin_request("test_plugin", "test_cmd", params, out_buffer, error);
    EXPECT_EQ(ret, HAS_ERR);
    EXPECT_FALSE(error.empty());
}

// 以下测试两种模式都适用

TEST_F(lua_plugin_test, plugin_request_no_bus)
{
    auto                 chip_no_bus = std::make_shared<dev::chip_base>();
    std::vector<uint8_t> params      = {0xAA};
    std::vector<uint8_t> out_buffer;
    std::string          error;

    EXPECT_THROW(chip_no_bus->plugin_request("test_plugin", "test_cmd", params, out_buffer, error),
                 mc::invalid_op_exception);
}

// Lua 沙箱运行环境需要 bootstrap.lua、mcskynet 和可加载的 mc.so。
static bool lua_sandbox_env_ready(const std::string& test_dir)
{
    std::ifstream bootstrap(test_dir + "/hwproxy/plugins/bootstrap.lua");
    if (!bootstrap.good()) {
        return false;
    }
    constexpr std::string_view suffix = "/opt/bmc/lualib";
    std::string                root;
    if (test_dir.size() >= suffix.size() &&
        test_dir.compare(test_dir.size() - suffix.size(), suffix.size(), suffix) == 0) {
        root = test_dir.substr(0, test_dir.size() - suffix.size());
    }
    std::ifstream skynet(root + "/opt/bmc/mcskynet/lualib/skynet.lua");
    if (!skynet.good()) {
        return false;
    }
    const std::string mc_so_path = root + "/opt/bmc/luaclib/mc.so";
    void*             mc         = dlopen(mc_so_path.c_str(), RTLD_NOW);
    if (mc == nullptr) {
        return false;
    }
    dlclose(mc);
    return true;
}

} // namespace