/*
 * Copyright (c) 2025 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 "fans_rs485_object.h"
#include <chrono>
#include <cstdlib>
#include <ctime>
#include <fcntl.h>
#include <grp.h> // getgrnam
#include <iomanip>
#include <mc/app/service.h>
#include <mc/app/task/task_mgmt.h>
#include <mc/filesystem.h>
#include <mc/log.h>
#include <mc/time.h>
#include <pwd.h> // getpwnam
#include <sstream>
#include <string>
#include <sys/stat.h> // chmod
#include <termios.h>
#include <unistd.h> // chown
#include <unistd.h>
#include "fan_rs485_object.h"
#include "internal/bus/bus_uart/uart.h"
#include "internal/manager.h"

namespace dev {

// 风扇执行 0x03 复位后,约需 3s 才能恢复通信。此处统一等待 5s(留余量),
// 在 start() 的复位遍历全部发起完毕后、逐个 activate 之前。
static constexpr uint32_t FAN_RESET_RECOVER_MS = 5000;

std::mutex FansRS485::s_uart_comm_mutex;

FansRS485::FansRS485() = default;

FansRS485::~FansRS485()
{
    // 先停通信线程再销毁成员, 防止 executor 访问已析构的 protocol/uart 指针(stop 幂等)
    stop();
}

bool FansRS485::start()
{
    elog("FansRS485: start() BEGIN");

    std::vector<mc::object_ptr> fan_objects;
    auto                        children = get_children();
    elog("FansRS485: start() - searching children, total_children_count=${count}", ("count", children.size()));

    for (auto& child : children) {
        if (!child) {
            continue;
        }
        std::string object_name = std::string(child->get_name());
        size_t      pos         = object_name.find_first_of("_");
        std::string prefix      = (pos != std::string::npos) ? object_name.substr(0, pos) : object_name;

        if (prefix == "Fan") {
            fan_objects.push_back(child);
            elog("FansRS485: start() - found FanRS485 child: ${name}", ("name", object_name));
        }
    }
    elog("FansRS485: start() Step1: found ${count} FanRS485 children", ("count", fan_objects.size()));

    m_fan_objects.clear();
    for (auto& fan_object : fan_objects) {
        if (fan_object == nullptr) {
            continue;
        }
        m_fan_objects.push_back(fan_object);
    }
    elog("FansRS485: start() Step2: stored ${count} fan objects in m_fan_objects", ("count", m_fan_objects.size()));

    elog("FansRS485: start() Step4: obtaining uart_bus from device_manager, bus_name='${name}'",
         ("name", m_uart_bus_name));

    if (m_uart_bus_name.empty()) {
        elog("FansRS485: start() FAILED at Step4: uart_bus_name not set in init()");
        return false;
    }

    if (m_fan_objects.empty()) {
        elog("FansRS485: start() FAILED at Step4: no fan objects available");
        return false;
    }
    auto first_fan = dynamic_cast<FanRS485*>(m_fan_objects[0].get());
    if (!first_fan) {
        elog("FansRS485: start() FAILED at Step4: first fan object is null");
        return false;
    }
    elog("FansRS485: start() Step4: first_fan found, name=${name}, uart_bus_ptr=${ptr}, protocol_ptr=${proto}",
         ("name", first_fan->get_object_name())("ptr", static_cast<void*>(first_fan->get_uart_bus()))(
             "proto", static_cast<void*>(first_fan->get_protocol())));

    auto& manager     = dev::device_manager::get_instance();
    auto  bus_variant = manager.find_object(m_uart_bus_name, dev::object_type::bus);

    if (!std::holds_alternative<std::shared_ptr<bus_base>>(bus_variant)) {
        elog("FansRS485: start() FAILED at Step4: uart_bus '${name}' not found in device_manager",
             ("name", m_uart_bus_name));
        return false;
    }

    auto bus_ptr = std::get<std::shared_ptr<bus_base>>(bus_variant);
    if (!bus_ptr) {
        elog("FansRS485: start() FAILED at Step4: uart_bus '${name}' found but ptr is null", ("name", m_uart_bus_name));
        return false;
    }

    m_uart_bus = std::dynamic_pointer_cast<bus_uart>(bus_ptr);
    if (!m_uart_bus) {
        elog("FansRS485: start() FAILED at Step4: bus '${name}' is not bus_uart type, actual type='${type}'",
             ("name", m_uart_bus_name)("type", bus_ptr->get_class_name()));
        return false;
    }

    elog("FansRS485: start() Step4: uart_bus obtained successfully, ptr=${ptr}, bus_name='${name}'",
         ("ptr", static_cast<void*>(m_uart_bus.get()))("name", m_uart_bus_name));

    elog("FansRS485: start() Step5: creating FanRS485CommService");
    m_comm_service = std::make_shared<FanRS485CommService>();
    elog("FansRS485: start() Step5: FanRS485CommService created, ptr=${ptr}",
         ("ptr", static_cast<void*>(m_comm_service.get())));

    elog(
        "FansRS485: start() Step6: calling m_comm_service->init(uart_bus=${bus}) (protocol will be passed per-command)",
        ("bus", static_cast<void*>(m_uart_bus.get())));
    if (!m_comm_service->init(m_uart_bus.get())) {
        elog("FansRS485: start() FAILED at Step6: m_comm_service->init() returned false");
        return false;
    }
    elog("FansRS485: start() Step6: m_comm_service->init() OK");

    elog("FansRS485: start() Step7: calling m_comm_service->start()");
    if (!m_comm_service->start()) {
        elog("FansRS485: start() FAILED at Step7: m_comm_service->start() returned false");
        return false;
    }
    elog("FansRS485: start() Step7: CommService started SUCCESSFULLY");

    elog("FansRS485: start() Step8: starting and activating ${count} fan objects", ("count", m_fan_objects.size()));
    int activated_count = 0;
    int failed_count    = 0;

    // Phase A: 先逐个 start() + set_comm_service,完成每个风扇自身的初始化
    // (m_slave_addr 从 Chip.Address 读出、m_em_protocol 创建)。注意:此时尚不 activate,
    // 因为复位必须在 start() 之后才能拿到有效的 addr/protocol(Step8.5 的修复点)。
    for (auto& fan_object_ptr : m_fan_objects) {
        if (fan_object_ptr == nullptr) {
            continue;
        }
        auto* fan_object = dynamic_cast<FanRS485*>(fan_object_ptr.get());
        if (fan_object == nullptr) {
            continue;
        }

        if (!fan_object->start()) {
            elog("FansRS485: start() Step8 PhaseA: fan ${name} start() FAILED",
                 ("name", fan_object->get_object_name()));
            failed_count++;
            continue;
        }
        elog("FansRS485: start() Step8 PhaseA: fan ${name} start() SUCCESS", ("name", fan_object->get_object_name()));

        fan_object->set_comm_service(m_comm_service);
        ilog("FansRS485: start() Step8 PhaseA: set_comm_service done for ${name}",
             ("name", fan_object->get_object_name()));
    }

    // Step8.5 (方案A): 注册前先对每个风扇执行 0x03 复位原子通信过程,
    // 清空其内存队列中驻留的待上报信息(如主机复位过程中残留的 GET_ALARM 等帧),
    // 使后续 activate 激活查询时队列首帧为 REGISTER(0x01) 自动上报。
    // 必须放在 start() 之后:此时 fan 对象的 m_slave_addr(真实地址)与 m_em_protocol 均已初始化,
    // 否则 reset_fan 会收到 addr=0 / protocol=null 而直接失败(原 bug)。
    // 单风扇复位失败不阻断其余风扇,仅记日志。
    // 注意:风扇复位后约需 3s 才能恢复通信。这里先逐个发起复位(发完即继续下一扇,
    // 不串行等待),待全部风扇复位发起完毕后,统一 sleep 5s 让所有风扇并行跨过恢复期,
    // 再进入 activate,避免每个风扇串行等 3s(4 扇共 12s)拖慢启动。
    {
        const int reset_retry_max = 3;
        for (auto& fan_object_ptr : m_fan_objects) {
            if (fan_object_ptr == nullptr) {
                continue;
            }
            auto* fan_object = dynamic_cast<FanRS485*>(fan_object_ptr.get());
            if (fan_object == nullptr) {
                continue;
            }
            if (!fan_object->is_basic_initialized()) {
                continue; // 仅对已成功 start 的扇复位
            }

            auto*   fan_protocol = fan_object->get_protocol();
            uint8_t fan_addr     = fan_object->get_slave_addr();
            bool    reset_ok     = false;
            for (int reset_try = 1; reset_try <= reset_retry_max; ++reset_try) {
                ilog("FansRS485: start() Step8.5: resetting fan ${name} (addr=${addr}) attempt ${try}/${max}",
                     ("name", fan_object->get_object_name())("addr", static_cast<int>(fan_addr))("try", reset_try)(
                         "max", reset_retry_max));
                reset_ok = m_comm_service->reset_fan(fan_addr, fan_protocol);
                if (reset_ok) {
                    break;
                }
                std::this_thread::sleep_for(std::chrono::milliseconds(200));
            }
            if (reset_ok) {
                ilog("FansRS485: start() Step8.5: fan ${name} (addr=${addr}) RESET SUCCESS, queue cleared",
                     ("name", fan_object->get_object_name())("addr", static_cast<int>(fan_addr)));
            } else {
                elog("FansRS485: start() Step8.5: fan ${name} (addr=${addr}) RESET FAILED after ${max} attempts, "
                     "continuing",
                     ("name", fan_object->get_object_name())("addr", static_cast<int>(fan_addr))("max",
                                                                                                 reset_retry_max));
            }
        }
        // 全部风扇复位发起完毕,统一等待 5s 让其完成内部复位并恢复通信(FAN_RESET_RECOVER_MS)。
        ilog("FansRS485: start() Step8.5: all fans reset issued, waiting ${ms}ms for fans to recover communication",
             ("ms", FAN_RESET_RECOVER_MS));
        std::this_thread::sleep_for(std::chrono::milliseconds(FAN_RESET_RECOVER_MS));
    }

    // Phase C: 复位+恢复期结束后,逐个 activate 激活查询(REGISTER 此时应为队列首帧)。
    for (auto& fan_object_ptr : m_fan_objects) {
        if (fan_object_ptr == nullptr) {
            continue;
        }
        auto* fan_object = dynamic_cast<FanRS485*>(fan_object_ptr.get());
        if (fan_object == nullptr) {
            continue;
        }
        if (!fan_object->is_basic_initialized()) {
            continue; // 跳过 start 失败的扇
        }

        if (fan_object->activate()) {
            elog("FansRS485: start() Step8 PhaseC: fan ${name} ACTIVATED SUCCESS",
                 ("name", fan_object->get_object_name()));
            activated_count++;

            std::this_thread::sleep_for(std::chrono::milliseconds(200));
            ilog("FansRS485: start() Step8 PhaseC: delay 200ms after ${name} to avoid RS485 bus conflict",
                 ("name", fan_object->get_object_name()));
        } else {
            elog("FansRS485: start() Step8 PhaseC: fan ${name} ACTIVATED FAILED",
                 ("name", fan_object->get_object_name()));
            failed_count++;
        }
    }
    elog("FansRS485: start() Step8: activation completed, success=${success}, failed=${fail}",
         ("success", activated_count)("fail", failed_count));

    m_fans.init();
    m_fans_oem.init();
    elog("FansRS485: start() Step9: Fans interfaces initialized");

    m_thread_pool = std::make_shared<mc::runtime::thread_pool>(1);
    m_thread_pool->start();
    elog("FansRS485: start() Step10: thread_pool started");

    m_fans.set_pwm_callback([this](const std::vector<double>& pwm_list) {
        return this->SetPWM(pwm_list);
    });

    m_fans.set_dump_fan_logs_callback([this](const std::vector<uint32_t>& fan_id_list, const std::string& tar_path,
                                             const std::string& caller_username) {
        return this->DumpFanLogs(fan_id_list, tar_path, caller_username);
    });

    m_fans.start();
    m_fans_oem.start();
    elog("FansRS485: start() Step11: Fans interfaces started");

    elog("FansRS485: start() COMPLETED, total_fans=${count}, activated=${act}, failed=${fail}",
         ("count", m_fan_objects.size())("act", activated_count)("fail", failed_count));
    return true;
}

FanRS485* FansRS485::get_first_fan_with_uart_bus()
{
    for (auto& fan_obj_ptr : m_fan_objects) {
        auto fan = dynamic_cast<FanRS485*>(fan_obj_ptr.get());
        if (fan && fan->get_uart_bus()) {
            return fan;
        }
    }
    return nullptr;
}

bool FansRS485::stop()
{
    // 幂等保护: 显式 stop() 与析构函数调用只生效一次
    if (m_stopped) {
        return true;
    }
    m_stopped = true;

    // 停机顺序(修复 UAF 时序):
    // 1. 先停 comm_service(join executor 线程, 清空队列并回调 nullopt):
    //    确保 executor 不再使用各 FanRS485 的 ElectromechanicalProtocol 裸指针,
    //    并让同步等待结果的线程池任务(DumpFanLogs)立即解除阻塞后自然退出。
    // 2. 再释放 thread_pool: 后台任务已因回调 nullopt 结束, 不会在对象销毁后执行
    //    post 捕获的 [this,...] lambda。
    // 3. 最后才 deactivate/stop 风扇对象(销毁其 m_em_protocol)。
    if (m_comm_service) {
        m_comm_service->stop();
    }

    if (m_thread_pool) {
        m_thread_pool.reset();
    }

    m_fans.stop();
    m_fans_oem.stop();

    for (auto& fan_object_ptr : m_fan_objects) {
        if (fan_object_ptr == nullptr) {
            continue;
        }
        auto fan_object = dynamic_cast<FanRS485*>(fan_object_ptr.get());
        if (fan_object == nullptr) {
            continue;
        }
        fan_object->deactivate();
        if (fan_object->stop()) {
            ilog("FansRS485: Stopped FanRS485 child object ${name}", ("name", fan_object->get_object_name()));
        } else {
            elog("FansRS485: Failed to stop FanRS485 child object ${name}", ("name", fan_object->get_object_name()));
        }
    }

    m_fan_objects.clear();

    ilog("FansRS485 stopped");
    return true;
}

bool FansRS485::init(mc::mutable_dict& csr_object, const mc::dict& connector)
{
    elog("FansRS485: init() BEGIN");

    try {
        FansRS485::from_variant(csr_object, *this);
        elog("FansRS485: init() - from_variant completed");

        elog("FansRS485: init() - parsing Buses from connector");

        if (connector.contains("Buses")) {
            try {
                auto buses = connector["Buses"].as<std::vector<std::string>>();
                if (!buses.empty()) {
                    m_uart_bus_name = buses[0];
                    elog("FansRS485: init() - UART bus name set to '${name}'", ("name", m_uart_bus_name));
                } else {
                    elog("FansRS485: init() FAILED - Buses array is empty");
                    return false;
                }
            } catch (const std::exception& e) {
                elog("FansRS485: init() FAILED - Error parsing Buses: ${err}", ("err", e.what()));
                return false;
            }
        } else {
            elog("FansRS485: init() FAILED - Buses field not found in connector");
            return false;
        }

        elog("FansRS485: init() COMPLETED, uart_bus_name='${name}'", ("name", m_uart_bus_name));
    } catch (const std::exception& e) {
        elog("FansRS485 init failed, exception: ${exception}", ("exception", e.what()));
        return false;
    }
    return true;
}

void FansRS485::from_variant(const mc::dict& d, dev::FansRS485& obj)
{
    mc::from_variant(d, obj);
}

void FansRS485::add_fan_objects(mc::object_ptr fan_object_ptr)
{
    if (fan_object_ptr != nullptr) {
        m_fan_objects.push_back(fan_object_ptr);
    }
}

uint8_t FansRS485::get_fan_count()
{
    return m_fan_objects.size();
}

uint8_t FansRS485::SetPWM(const std::vector<double>& pwm_list)
{
    dlog("FansRS485::SetPWM BEGIN - pwm_list_size=${size}, fan_count=${fan_count}, pwm_values=[${values}]",
         ("size", pwm_list.size())("fan_count", get_fan_count())("values", pwm_list));

    if (pwm_list.empty() || pwm_list.size() != get_fan_count()) {
        wlog("FansRS485 SetPWM: wrong pwm number, expected ${expected}, got ${actual}",
             ("expected", get_fan_count())("actual", pwm_list.size()));
        return 1;
    }

    const auto& fan_objects = get_fan_objects();
    dlog("FansRS485::SetPWM - fan_objects_count=${count}, starting PWM setting loop", ("count", fan_objects.size()));

    // 逐台同步下发并聚合结果: 0x24 未被从机确认(超时/固件拒绝)的风扇不计成功,
    // ExpectedPWM 仅在下发确认成功后更新, 避免thermal侧误认为PWM已生效。
    uint8_t failed_count = 0;

    for (size_t index = 0; index < fan_objects.size() && index < pwm_list.size(); ++index) {
        dlog("FansRS485::SetPWM - loop[${index}]: processing fan, pwm_value=${pwm}",
             ("index", index)("pwm", pwm_list[index]));

        auto fan_obj = dynamic_cast<FanRS485*>(fan_objects[index].get());
        if (fan_obj == nullptr) {
            elog("FansRS485::SetPWM - loop[${index}]: dynamic_cast FAILED, fan_object is not FanRS485",
                 ("index", index));
            failed_count++;
            continue;
        }

        dlog("FansRS485::SetPWM - loop[${index}]: fan_id=${fan_id}, calling set_pwm_duty_cycle with pwm=${pwm}",
             ("index", index)("fan_id", fan_obj->m_fan.FanId.get_value())("pwm", pwm_list[index]));

        if (!fan_obj->set_pwm_duty_cycle(pwm_list[index])) {
            elog("FansRS485::SetPWM - loop[${index}]: fan_id=${fan_id} set_pwm_duty_cycle FAILED "
                 "(not confirmed by slave), ExpectedPWM NOT updated",
                 ("index", index)("fan_id", fan_obj->m_fan.FanId.get_value()));
            failed_count++;
            continue;
        }

        dlog("FansRS485::SetPWM - loop[${index}]: ExpectedPWM set to ${pwm} for fan_id=${fan_id}",
             ("index", index)("pwm", pwm_list[index])("fan_id", fan_obj->m_fan.FanId.get_value()));

        fan_obj->m_fan_metrics.ExpectedPWM.set_value(pwm_list[index]);
    }

    dlog("FansRS485::SetPWM COMPLETE - processed ${processed} fans, failed=${failed}, pwm_list_size=${size}",
         ("processed", fan_objects.size())("failed", failed_count)("size", pwm_list.size()));

    if (failed_count > 0) {
        elog("FansRS485 SetPWM: ${failed}/${total} fans failed to confirm PWM",
             ("failed", failed_count)("total", pwm_list.size()));
        return 1;
    }

    ilog("FansRS485 SetPWM: successfully set PWM for ${count} fans", ("count", pwm_list.size()));
    return 0;
}

uint32_t FansRS485::DumpFanLogs(const std::vector<uint32_t>& fan_id_list, const std::string& tar_path,
                                const std::string& caller_username)
{
    if (fan_id_list.empty()) {
        elog("FansRS485 DumpFanLogs: fan_id_list is empty");
        return 0;
    }

    if (tar_path.empty() || tar_path.substr(0, 5) != "/tmp/") {
        elog("FansRS485 DumpFanLogs: invalid tar_path ${path}", ("path", tar_path));
        return 0;
    }

    // 参考 RAID task_mgmt 模式: D-Bus 线程创建 Task 资源并立即返回 task_id,
    // 后台线程池批量同步收集多扇日志 + tar 打包, 完成后 update_task 更新状态.
    // TaskMgmt 实例由 mc::app::service 持有(非全局单例), 经 svc->task_mgmt() 访问.
    auto* svc = static_cast<mc::app::service*>(get_service());
    if (svc == nullptr) {
        elog("FansRS485 DumpFanLogs: service is null, cannot create task");
        return 0;
    }
    auto [create_result, err_msg, task_id] =
        svc->task_mgmt().create_task("DumpFanLogs", mc::string(this->get_object_path()), 30, []() {
        elog("FansRS485: DumpFanLogs task TIMEOUT");
    }, {{"Description", mc::string("收集风扇日志")}, {"Stage", mc::string("收集中")}});

    if (create_result != mc::app::task::CreateResult::Success) {
        elog("FansRS485 DumpFanLogs: create_task failed: ${msg}", ("msg", err_msg));
        return 0;
    }

    ilog("FansRS485 DumpFanLogs: task ${id} created, collecting ${n} fans' logs async, caller=${caller}",
         ("id", task_id)("n", fan_id_list.size())("caller", caller_username.empty() ? "unknown" : caller_username));

    // 捕获参数到后台线程池执行(dump_log_info 同步多帧读会阻塞, 不能在 D-Bus 线程)
    auto fan_ids = fan_id_list;
    auto tar     = tar_path;
    auto caller  = caller_username;
    m_thread_pool->get_executor().post([this, svc, fan_ids, tar, task_id, caller]() {
        uint32_t       success_count = 0;
        const uint32_t total_count   = static_cast<uint32_t>(fan_ids.size());

        // 安全改进: 临时文件在 /var/log 下创建(非 /tmp), 避免被外部访问
        // /var/log 仅 root 可写, 临时文件 chmod 0640 限制访问
        auto              now      = std::chrono::system_clock::now();
        auto              now_time = std::chrono::system_clock::to_time_t(now);
        std::stringstream ss;
        ss << "/var/log/fan_logs_" << std::put_time(std::localtime(&now_time), "%Y%m%d_%H%M%S");
        std::string temp_dir = ss.str();
        mc::filesystem::create_directories(temp_dir);

        for (size_t i = 0; i < fan_ids.size(); ++i) {
            uint32_t fan_id = fan_ids[i];

            FanRS485* target_fan = nullptr;
            for (auto& fan_obj_ptr : m_fan_objects) {
                auto fan_obj = dynamic_cast<FanRS485*>(fan_obj_ptr.get());
                if (fan_obj && fan_obj->m_fan.FanId.get_value() == fan_id) {
                    target_fan = fan_obj;
                    break;
                }
            }

            if (!target_fan) {
                wlog("FansRS485 DumpFanLogs: fan ${id} not found", ("id", fan_id));
                continue;
            }

            std::string fan_log_path = temp_dir + "/fan_" + std::to_string(fan_id) + ".log";

            if (target_fan->dump_log_info(fan_log_path)) {
                // 临时日志文件权限: owner读写, group只读 (0640)
                chmod(fan_log_path.c_str(), S_IRUSR | S_IWUSR | S_IRGRP);
                success_count++;
                ilog("FansRS485 DumpFanLogs: fan ${id} log collected successfully", ("id", fan_id));
            } else {
                elog("FansRS485 DumpFanLogs: fan ${id} log collection failed", ("id", fan_id));
            }

            // 更新进度
            mc::dict progress_data;
            progress_data["Progress"] = static_cast<int64_t>((i + 1) * 100 / total_count);
            svc->task_mgmt().update_task(task_id, progress_data);
        }

        // tar 打包所有日志到一个压缩包
        std::string tar_cmd = "cd " + temp_dir + " && tar -czf " + tar + " *.log";
        int         ret     = system(tar_cmd.c_str());

        // 安全改进: 最终 tar 文件赋权给调用方用户(非 root)
        // 若 caller 为空或获取失败, 回退到 secbox 用户(参考项目中 NIC/NCSI 日志收集的做法)
        std::string    chown_user = caller.empty() ? "secbox" : caller;
        struct passwd* pw         = getpwnam(chown_user.c_str());
        struct group*  gr         = getgrnam(chown_user.c_str());
        if (pw && gr) {
            if (chown(tar.c_str(), pw->pw_uid, gr->gr_gid) != 0) {
                elog("FansRS485 DumpFanLogs: chown to ${user} failed for ${path}", ("user", chown_user)("path", tar));
            } else {
                ilog("FansRS485 DumpFanLogs: tar file chown to ${user} (uid=${uid}, gid=${gid})",
                     ("user", chown_user)("uid", pw->pw_uid)("gid", gr->gr_gid));
            }
        } else {
            wlog("FansRS485 DumpFanLogs: user ${user} not found, chown skipped", ("user", chown_user));
        }
        // 最终 tar 文件权限: owner读写, group只读 (0640)
        chmod(tar.c_str(), S_IRUSR | S_IWUSR | S_IRGRP);

        // 清理临时目录(/var/log 下的临时文件)
        mc::filesystem::remove_all(temp_dir);

        // 更新任务最终状态
        mc::dict data;
        data["Progress"] = static_cast<int64_t>(100);
        if (ret == 0 && success_count > 0) {
            data["State"] = mc::string("Completed");
            ilog("FansRS485 DumpFanLogs: task ${tid} COMPLETED, success=${ok}/${total}, path=${path}",
                 ("tid", task_id)("ok", success_count)("total", total_count)("path", tar));
        } else {
            data["State"]  = mc::string("Exception");
            data["Status"] = mc::string("Error");
            elog("FansRS485 DumpFanLogs: task ${tid} EXCEPTION, ret=${ret}, success=${ok}/${total}",
                 ("tid", task_id)("ret", ret)("ok", success_count)("total", total_count));
        }
        svc->task_mgmt().update_task(task_id, data);
    });

    return task_id;
}

} // namespace dev

MC_REFLECT(dev::FansRS485, ((m_fans, "bmc.dev.Fans"))((m_fans_oem, "bmc.dev.Fans.Oem")))