#include "IpcDBus.h"

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

#include "src/core/CoreService.h"

IpcDBus::IpcDBus(CoreService* coreService, const QString& role, QObject* parent)
    : QObject(parent),
      m_coreService(coreService),
      m_role(role)
{
}

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;
}

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

