#include "IpcDBus.h"

#include <QCoreApplication>
#include <QDateTime>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonParseError>

#include "api/ipc_dbus/CommandDispatcher.h"
#include "src/core/CoreService.h"

IpcDBus::IpcDBus(CoreService* coreService, const QString& role, QObject* parent)
    : QObject(parent),
      m_coreService(coreService),
      m_role(role),
      m_dispatcher(std::make_unique<softbus::api::ipc::CommandDispatcher>())
{
}

IpcDBus::~IpcDBus() = default;

bool IpcDBus::isRunning() const
{
    if (!m_coreService) {
        return false;
    }
    return m_coreService->isInitialized();
}

QString IpcDBus::ping() const
{
    return QStringLiteral("pong");
}

QString IpcDBus::getVersion() const
{
    return QCoreApplication::applicationVersion();
}

QString IpcDBus::getStatus() const
{
    QJsonObject obj;
    obj.insert(QStringLiteral("service"), QStringLiteral("com.softbus.Daemon"));
    obj.insert(QStringLiteral("objectPath"), QStringLiteral("/com/softbus/Daemon"));
    obj.insert(QStringLiteral("interface"), QStringLiteral("com.softbus.Daemon"));
    obj.insert(QStringLiteral("pid"), static_cast<qint64>(QCoreApplication::applicationPid()));
    obj.insert(QStringLiteral("role"), m_role);
    obj.insert(QStringLiteral("running"), isRunning());
    obj.insert(QStringLiteral("timestampMs"), static_cast<qint64>(QDateTime::currentMSecsSinceEpoch()));

    const QJsonDocument doc(obj);
    return QString::fromUtf8(doc.toJson(QJsonDocument::Compact));
}

qint64 IpcDBus::getPid() const
{
    return static_cast<qint64>(QCoreApplication::applicationPid());
}

void IpcDBus::shutdown()
{
    if (m_coreService) {
        m_coreService->shutdown();
    }
    QCoreApplication::quit();
}

bool IpcDBus::reloadConfig()
{
    // 占位：后续移植配置系统时在这里触发 reload
    return false;
}

QString IpcDBus::executeCommand(const QString& requestJson)
{
    auto makeResponse = [](const QString& id, int code, const QString& message, const QJsonObject& data) {
        QJsonObject o;
        o.insert(QStringLiteral("id"), id);
        o.insert(QStringLiteral("code"), code);
        o.insert(QStringLiteral("message"), message);
        o.insert(QStringLiteral("data"), data);
        return QString::fromUtf8(QJsonDocument(o).toJson(QJsonDocument::Compact));
    };

    QJsonParseError err;
    const QJsonDocument doc = QJsonDocument::fromJson(requestJson.toUtf8(), &err);
    if (err.error != QJsonParseError::NoError || !doc.isObject()) {
        return makeResponse(QString(), 4000, QStringLiteral("invalid_json"), {});
    }
    const QJsonObject req = doc.object();
    const QString id = req.value(QStringLiteral("id")).toString();
    const QString action = req.value(QStringLiteral("action")).toString();
    const QJsonObject params = req.value(QStringLiteral("params")).toObject();
    if (action.isEmpty() || !m_dispatcher) {
        return makeResponse(id, 4003, QStringLiteral("invalid_action"), {});
    }
    const auto result = m_dispatcher->dispatch(action, params);
    return makeResponse(id, result.code, result.message, result.data);
}

void IpcDBus::updateLoadInfo()
{
    // 预留：后续可在此周期性采样 CPU/内存/队列长度等指标，并通过 getStatus() 输出
}

