/*
 * Copyright © 2025 Volla Systeme GmbH.
 *
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 3,
 * as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "sysfs_hbm.h"
#include "event_loop_handler_registration.h"
#include "filesystem.h"
#include "src/core/log.h"
#include <deviceinfo/deviceinfo.h>

#include <algorithm>
#include <fstream>
#include <stdexcept>
#include <vector>

namespace
{
char const* const log_tag = "SysfsHBM";
auto const null_handler = [](bool){};
}  // namespace

repowerd::SysfsHBM::SysfsHBM(
    std::shared_ptr<Log> const& log,
    std::shared_ptr<Filesystem> const& filesystem)
    : log{log},
      filesystem{filesystem},
      sysfs_hbm_file{""},     // Initialize with a dummy/empty path, will be set if valid
      hbm_enabled_value{"1"},
      hbm_disabled_value{"0"},
      event_loop{"SysfsHBM"},
      hbm_handler(null_handler)
{
    DeviceInfo device_info;
    std::string hbm_path_str = device_info.get("HBMSysfsPath", "");

    if (hbm_path_str.empty()) {
        log->logDebug(log_tag, "HBMSysfsPath not found in DeviceInfo. HBM support disabled.");
        throw std::runtime_error("HBMSysfsPath not found in DeviceInfo");
    }

    if (!filesystem->is_regular_file(hbm_path_str)) {
        log->logDebug(log_tag, "HBM control file %s not found or not a regular file. HBM support disabled.", hbm_path_str.c_str());
        std::string error_message = "HBM control file ";
        error_message += hbm_path_str;
        error_message += " not found or not a regular file";
        throw std::runtime_error(error_message);
    }

    this->sysfs_hbm_file = repowerd::Path{hbm_path_str};

    log->logDebug(log_tag, "Using HBM control file %s", hbm_path_str.c_str());
    log->logDebug(log_tag, "HBM values: enabled='%s', disabled='%s'",
            hbm_enabled_value.c_str(), hbm_disabled_value.c_str());
}

void repowerd::SysfsHBM::set_enabled(bool enabled)
{
    if (get_enabled() == enabled)
        return;

    try {
        auto ostream = filesystem->ostream(sysfs_hbm_file);
        *ostream << (enabled ? hbm_enabled_value : hbm_disabled_value);
        ostream->flush();
    } catch (std::exception const& e) {
        log->logWarning(log_tag, "Failed to set HBM state: %s", e.what());
        return;
    }

    hbm_handler(enabled);
}

bool repowerd::SysfsHBM::get_enabled()
{
    try {
        auto istream = filesystem->istream(sysfs_hbm_file);
        std::string current_value;
        *istream >> current_value;

        if (current_value == hbm_enabled_value)
            return true;
        else if (current_value == hbm_disabled_value)
            return false;
        else {
            log->logDebug(log_tag, "Unexpected value in HBM sysfs file: %s", current_value.c_str());
            return false;
        }
    }
    catch (std::exception const& e) {
        log->logWarning(log_tag, "Failed to read HBM state: %s", e.what());
        return false;
    }
}

bool repowerd::SysfsHBM::is_supported() const
{
    return true;
}

repowerd::HandlerRegistration repowerd::SysfsHBM::register_high_brightness_mode_handler(
    HighBrightnessModeHandler const &handler)
{
    return EventLoopHandlerRegistration(
        event_loop,
        [this, handler] { hbm_handler = handler;},
        [this] { hbm_handler = null_handler; });
}
