-- 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 scan = require('scan')
local log = require('mc.logging')
local class = require('mc.class')
local object_defs = require('object_defs')
local skynet = require('skynet')
pcall(require, 'traceback.debug_chip')
local chip = require('chip')
local common = require('common')

local CLASS_JTAG_SWITCH = 'JtagSwitch'
local CLASS_CHIP = 'Chip'

-- 根据对象名称提取class_name
local function get_class_type(object_name)
    return string.match(object_name, '^[^_]+')
end

local dispatch = class()

function dispatch:ctor(is_main_app, bus_object_name)
    self.is_main_app = is_main_app
    self.bus_object_name = bus_object_name

    -- 每条bus及下所有chip构成一个scan
    self.scans = {}

    -- 缓存拓扑结构中的mux与chip连接关系
    self.mux_data = {}
end

function dispatch:new_work_pre_device_bus(service, buses, pre_device, chip_name, position)
    if not buses[pre_device] then
        if self.is_main_app then
            log:error('position: %s chip: %s get bus object failed pre_device: %s', position, chip_name, pre_device)
            return
        end
        log:notice(
            'position: %s chip: %s work service start to get bus object, pre_device: %s',
            position,
            chip_name,
            pre_device
        )
        local bus_object = skynet.call('.hwproxy', 'lua', 'get_bus_object', pre_device)
        if bus_object == nil then
            log:error(
                'position: %s chip: %s request main service bus object failed: %s',
                position,
                chip_name,
                pre_device
            )
            return
        end
        local ok, bus = pcall(service.new_bus, service, bus_object)
        if not ok then
            log:warn(
                'position: %s chip: %s work service bus_object not exist, and create bus %s failed, msg: %s',
                position,
                chip_name,
                pre_device,
                bus
            )
            return
        end
        buses[pre_device] = bus
        log:notice(
            'position: %s chip: %s work service bus_object not exist, get %s from main service success',
            position,
            chip_name,
            pre_device
        )
    end
end

local function get_vchip_name(pre_device)
    return 'VChip_' .. pre_device
end

local function new_vchip(vchip_name)
    return {
        name = vchip_name,
        class_name = 'Chip',
        Address = 0xFF,
        AddrWidth = 1,
        OffsetWidth = 0,
    }
end

function dispatch:add_vchip(service, buses, pre_device)
    local vchip_name = get_vchip_name(pre_device)
    local class_name = get_class_type(pre_device)
    if object_defs[class_name].support_bus_block_io and not service.chips[vchip_name] then
        local vchip_obj = new_vchip(vchip_name)
        local new_chip = chip.new(vchip_obj)
        new_chip:add_l_bus(buses[pre_device])
        self.scans[pre_device]:add_chip(new_chip)
        service.chips[vchip_name] = new_chip
    end
end

local function merge_object(service, chip_topo_obj, chip_name, chip_objs)
    service.chips[chip_name] = chip_topo_obj.chip
    chip_topo_obj.ref_count = chip_topo_obj.ref_count + 1
    chip_topo_obj.chip.ref_count = chip_topo_obj.chip.ref_count + 1
    service.chips[chip_name]:add_tree_obj(chip_objs[chip_name])
end

local function handle_chip_merge(service, chip_topo_obj, chip_name, chip_objs)
    local old_name = chip_topo_obj.chip.name
    local old_type = old_name:match('^(.-)_')
    local new_type = chip_name:match('^(.-)_')

    local old_position = old_name:match('_([^_]*)$')
    local new_position = chip_name:match('_([^_]*)$')

    local is_same_type = old_type == new_type
    local is_same_position = old_position == new_position

    -- 同级配置中相同地址不同类型的器件不应进行对象合并,但有已存配置,暂时无法限制,做提示处理
    if is_same_position and not is_same_type then
        log:warn(
            'Same bus contains devices with identical addresses, '
                .. 'likely misconfiguration that may cause functional issues, from %s to %s',
            chip_name,
            old_name
        )
    end

    if not is_same_position and not is_same_type then
        log:warn('merge different type chip object from %s to %s', chip_name, old_name)
    end

    if is_same_position and is_same_type then
        log:notice('merge same type chip object in the same position from %s to %s', chip_name, old_name)
    end

    merge_object(service, chip_topo_obj, chip_name, chip_objs)
    return true
end

-- 前级是总线Bus
function dispatch:predevice_bus_handle(service, buses, chip_objs, pre_device, chip_name, position)
    -- 不存在scan时先创建scan
    local error_str = string.format(
        'position: %s, chip: %s, start creat predevice bus handle, pre_device: %s,'
            .. 'is main app: %s, not scans: %s, not buses: %s',
        position,
        chip_name,
        pre_device,
        self.is_main_app,
        not self.scans[pre_device],
        not buses[pre_device]
    )
    log:notice(error_str)
    log:hw_stream_notice(error_str)

    if not self.scans[pre_device] then
        self:new_work_pre_device_bus(service, buses, pre_device, chip_name, position)
        if buses[pre_device] == nil then
            return
        end
        self.scans[pre_device] = scan.new(buses[pre_device])
        self:add_vchip(service, buses, pre_device)
        if buses[pre_device].need_scan then
            self.scans[pre_device]:run()
        end
    end

    if chip_objs[chip_name] == nil then
        return
    end

    if not service.chip_topo[pre_device] then
        service.chip_topo[pre_device] = {}
    end

    local default_addr = get_class_type(chip_name) == CLASS_JTAG_SWITCH and 0xfe or 0xff
    --[[
    器件合并机制说明1:前级器件(总线)相同的场景下,对于Address相同的器件会进行合并。
    器件合并机制说明2:SPIFlash器件没有Address概念,同个总线下不同Flash器件是通过片选ChipSelect区分的。不同片选属于不同器件,不能进行合并。
                     SPIFlash的前级器件下只支持下挂SPIFlash器件,因此不存在ChipSelect和其他器件类型的Address属性冲突误合并的场景
    --]]
    local address = chip_objs[chip_name].Address or chip_objs[chip_name].ChipSelect or default_addr
    local do_object_register = true
    if not service.chip_topo[pre_device][address] then
        local new_chip = chip.new(chip_objs[chip_name])
        new_chip:add_tree_obj(chip_objs[chip_name])
        new_chip:add_l_bus(buses[pre_device])
        if not self.is_main_app and get_class_type(chip_name) == CLASS_CHIP then
            -- 通用器件类型初始化寄存器配置
            new_chip:chip_init(chip_objs[chip_name].RegisterConfig)
        end
        self.scans[pre_device]:add_chip(new_chip)

        service.chip_topo[pre_device][address] = { chip = new_chip, ref_count = 1 }
        service.chips[chip_name] = new_chip
    else
        local chip_topo_obj = service.chip_topo[pre_device][address]
        do_object_register = handle_chip_merge(service, chip_topo_obj, chip_name, chip_objs)
    end

    if not self.is_main_app and chip_objs[chip_name].need_register and do_object_register then
        log:hw_stream_info(
            'position: %s chip: %s send object register message, pre_device: %s',
            position,
            chip_name,
            pre_device
        )
        skynet.send('.hwproxy', 'lua', 'object_register', chip_name)
    end
end

-- 前级是通道Mux
function dispatch:predevice_chip_handle(service, chip_objs, pre_device, chip_name)
    if not self.mux_data[pre_device] then
        if self.is_main_app then
            log:error('chip: %s pre chip not exist, add chip r_chips failed, pre_device is %s', chip_name, pre_device)
        end
        return
    end

    -- 通过mux找到前级chip,如Pca9545
    local pre_chip_name = self.mux_data[pre_device].pre_device
    local channel_id = self.mux_data[pre_device].channel_id
    local l_chip = service.chips[pre_chip_name]
    if l_chip == nil then
        return
    end

    if not service.chip_topo[pre_chip_name] then
        service.chip_topo[pre_chip_name] = {}
    end

    if not service.chip_topo[pre_chip_name][channel_id] then
        service.chip_topo[pre_chip_name][channel_id] = {}
    end

    local default_addr = get_class_type(chip_name) == CLASS_JTAG_SWITCH and 0xfe or 0xff
    local address = chip_objs[chip_name].Address or default_addr
    local do_object_register = true
    if not service.chip_topo[pre_chip_name][channel_id][address] then
        local r_chip = chip.new(chip_objs[chip_name])
        local host_bus = l_chip.host_bus
        r_chip:add_tree_obj(chip_objs[chip_name])
        r_chip:add_l_bus(host_bus)
        r_chip:add_l_chip(l_chip)
        l_chip:add_r_chip(r_chip, channel_id)
        if not self.is_main_app and get_class_type(chip_name) == CLASS_CHIP then
            -- 通用器件类型初始化寄存器配置
            r_chip:chip_init(chip_objs[chip_name].RegisterConfig)
        end

        service.chip_topo[pre_chip_name][channel_id][address] = { chip = r_chip, ref_count = 1 }
        service.chips[chip_name] = r_chip
    else
        local chip_topo_obj = service.chip_topo[pre_chip_name][channel_id][address]
        do_object_register = handle_chip_merge(service, chip_topo_obj, chip_name, chip_objs)
    end

    if not self.is_main_app and chip_objs[chip_name].need_register and do_object_register then
        skynet.send('.hwproxy', 'lua', 'object_register', chip_name)
    end
end

-- 按顺序递归处理拓扑生成
function dispatch:generate_topo_in_order(service, buses, chip_objs, mux_data, topo_data, pre_device, position)
    -- 递归终止条件,topo_data中不存在以pre_device为父节点的链路
    if not topo_data[pre_device] then
        return
    end

    -- 获取前级器件类型,前级器件类型未注册时无法确定其下级处理方式,直接跳过
    local pre_def = object_defs[get_class_type(pre_device)]
    if not pre_def then
        log:error('unknown pre_device class, pre_device: %s, position: %s', pre_device, position)
        return
    end
    local pre_type = pre_def.type
    if self.bus_object_name then
        -- 总线是否与当前work服务的bus匹配
        if pre_type == 'Bus' and self.bus_object_name ~= pre_device then
            return
        end

        if common.mux_class[get_class_type(pre_device)] and not mux_data[pre_device] then
            return
        end
    end
    local error_str = string.format(
        'position: %s, start to process objs in pre_type: %s, topo_data[%s]' .. ', objs nums: %s',
        position,
        pre_type,
        pre_device,
        #topo_data[pre_device]
    )
    log:notice(error_str)
    log:hw_stream_notice(error_str)
    for _, obj in pairs(topo_data[pre_device]) do
        -- 当前器件类型
        log:hw_stream_info('position: %s obj: %s start to process in topo_data[%s]', position, obj, pre_device)
        local type = get_class_type(obj)
        if type == 'Connector' or (object_defs[type] and object_defs[type].type == 'Bus') then
            goto continue
        end

        -- 若当前chip为mux,更新mux_data信息
        if common.mux_class[type] then
            if mux_data[obj] == nil then
                goto continue
            end

            self.mux_data[obj] = { pre_device = pre_device, channel_id = mux_data[obj].channel_id }
            mux_data[obj].pre_device = pre_device
            goto continue
        end

        pcall(function()
            if pre_type == 'Bus' then
                self:predevice_bus_handle(service, buses, chip_objs, pre_device, obj, position)
            else
                self:predevice_chip_handle(service, chip_objs, pre_device, obj)
            end
        end)

        ::continue::
        -- 若当前结构还存在拓扑结构,继续处理当前chip的下一级
        self:generate_topo_in_order(service, buses, chip_objs, mux_data, topo_data, obj, position)
    end
end

function dispatch:generate_topo_link(service, buses, chip_objs, mux_data, topo_data, position)
    if not topo_data or not topo_data.Anchor then
        log:error('Generate topo link failed')
        return
    end

    for _, pre_device in pairs(topo_data.Anchor) do
        self:generate_topo_in_order(service, buses, chip_objs, mux_data, topo_data, pre_device, position)
    end
end

function dispatch:remove_topo_in_order(chips, topo_data, pre_device)
    if not topo_data[pre_device] then
        return
    end

    -- 前级器件类型未注册时无法确定其下级处理方式,直接跳过
    local pre_def = object_defs[get_class_type(pre_device)]
    if not pre_def then
        log:error('unknown pre_device class, pre_device: %s', pre_device)
        return
    end
    local pre_type = pre_def.type
    if self.bus_object_name then
        -- 总线是否与当前work服务的bus匹配
        if pre_type == 'Bus' and self.bus_object_name ~= pre_device then
            return
        end

        if common.mux_class[get_class_type(pre_device)] and not self.mux_data[pre_device] then
            return
        end
    end

    for _, chip_name in pairs(topo_data[pre_device]) do
        -- 只需删除根节点所在子树,无需从叶子节点开始删除
        local type = get_class_type(chip_name)
        if type == 'Connector' or common.mux_class[type] then
            goto continue
        end

        if pre_type == 'Bus' then
            if self.scans[pre_device] then
                self.scans[pre_device]:delete_chip(chip_name)
            end
        else
            if not self.mux_data[pre_device] then
                log:error(
                    'chip: %s pre chip not exist, delete its r_chips failed, pre_device is %s',
                    chip_name,
                    pre_device
                )
                return
            end
            local real_pre_device = self.mux_data[pre_device].pre_device
            chips[real_pre_device]:delete_r_chip(chip_name)
        end

        ::continue::
    end
end

function dispatch:remove_topo_link(chips, topo_data)
    if not topo_data or not topo_data.Anchor then
        log:error('Remove topo link failed')
        return
    end

    for _, pre_device in pairs(topo_data.Anchor) do
        self:remove_topo_in_order(chips, topo_data, pre_device)
    end
end

return dispatch