/*
 * 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 "interface/chip.h"

#include <algorithm>
#include <mc/engine.h>
#include <mc/log.h>
#include "../ssu_card.h"

namespace dev {

std::vector<uint8_t> SSUChip::BlockIORead(uint32_t offset, uint32_t length)
{
    auto* owner = dynamic_cast<dev::ssu_card*>(get_owner());
    if (!owner) {
        elog("SSUChip: BlockIORead owner is not ssu_card");
        return {};
    }

    const int ssu_slot = static_cast<int>(owner->get_ssu_slot());
    auto*     oob      = owner->get_ssu_oob();
    if (!oob) {
        elog("SSUChip[ssu_slot=${ssu_slot}]: BlockIORead failed, mctp endpoint not exist", ("ssu_slot", ssu_slot));
        MC_THROW(mc::runtime_exception, "SSUChip[ssu_slot=${ssu_slot}]: BlockIORead failed, mctp endpoint not exist",
                 ("ssu_slot", ssu_slot));
    }

    std::string elabel;
    if (!oob->get_elabel(elabel)) {
        elog("SSUChip[ssu_slot=${ssu_slot}]: BlockIORead get_elabel failed", ("ssu_slot", ssu_slot));
        return {};
    }

    // get_elabel 返回完整电子标签(当前为 2048 字节),按入参 offset/length 截取;
    // 超出电子标签末尾的部分补 0
    const std::vector<uint8_t> full_elabel(elabel.begin(), elabel.end());
    std::vector<uint8_t>       result(length, 0);
    const size_t               begin = static_cast<size_t>(offset);
    if (begin < full_elabel.size() && length > 0) {
        const size_t copy_len = std::min(static_cast<size_t>(length), full_elabel.size() - begin);
        std::copy(full_elabel.begin() + begin, full_elabel.begin() + begin + copy_len, result.begin());
    }

    ilog("SSUChip[ssu_slot=${ssu_slot}]: BlockIORead, offset=${offset}, length=${length}, "
         "elabel_len=${elabel_len}, result_len=${result_len}",
         ("ssu_slot", ssu_slot)("offset", offset)("length", length)("elabel_len", full_elabel.size())("result_len",
                                                                                                      result.size()));
    return result;
}

} // namespace dev

MC_REFLECT(dev::SSUChip)