#include "CoreService.h"

#include <QFile>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray> 
#include <QDir>
#include <QFileInfo>

#include "utils/logs/logging.h"
#include "device_bus/DeviceBus.h"
#include "message_bus/pipeline/PayloadRef.h"
#include "message_bus/pipeline/PipelineContext.h"

CoreService* CoreService::instance()
{
    static CoreService inst;
    return &inst;
}

CoreService::CoreService(QObject* parent)
    : QObject(parent)
    , m_initialized(false)
{
}

CoreService::~CoreService()
{

}

bool CoreService::initialize()
{
    if (m_initialized) {
        LOG_WARNING() << "CoreService already initialized";
        return true;
    }

    LOG_INFO() << "CoreService initializing";
    qRegisterMetaType<softbus::message_bus::pipeline::PayloadRef>("softbus::message_bus::pipeline::PayloadRef");
    qRegisterMetaType<softbus::message_bus::pipeline::PipelineContext>("softbus::message_bus::pipeline::PipelineContext");

    // 1. 解析配置路径（放在用户 home 下的相对固定目录：~/softbus/config）
    const QString configPath =
        QDir::homePath() + QStringLiteral("/softbus/config/daemon_config.json");

    auto& bus = softbus::device_bus::DeviceBus::instance();
    bus.setConfigPath(configPath);

    QJsonObject root;
    const QFileInfo fi(configPath);
    if (!fi.exists()) {
        LOG_WARNING() << "CoreService: config not found, skip load:" << configPath;
        root.insert(QStringLiteral("device_tree"), QJsonArray{});
        bus.markDeviceTreeDirty(); // 首次启动：退出时至少会落一个最小配置文件
    } else {
        QFile f(configPath);
        if (!f.open(QIODevice::ReadOnly | QIODevice::Text)) {
            LOG_ERROR() << "CoreService: failed to open" << configPath;
            return false;
        }

        const QByteArray data = f.readAll();
        f.close();

        QJsonParseError pe;
        const QJsonDocument doc = QJsonDocument::fromJson(data, &pe);
        if (pe.error != QJsonParseError::NoError || !doc.isObject()) {
            LOG_ERROR() << "CoreService: invalid JSON in" << configPath << ":" << pe.errorString();
            return false;
        }

        root = doc.object();
    }

    // 2. 初始化 device_bus（交给 DeviceBus facade 处理具体设备）
    if (!bus.initialize(root)) {
        return false;
    }

    m_initialized = true;
    return true;
}

void CoreService::shutdown()
{
    if (!m_initialized) {
        LOG_DEBUG() << "CoreService shutdown called while not initialized";
        return;
    }

    LOG_INFO() << "CoreService shutting down";
    softbus::device_bus::DeviceBus::instance().shutdown();
    m_initialized = false;
}

bool CoreService::isInitialized() const
{
    return m_initialized;
}
