#include <QCoreApplication>
#include <QCommandLineParser>
#include <QDBusConnection>
#include <QDBusError>
#include <signal.h>
#include "src/utils/logs/logging.h"
#include "src/core/CoreService.h"
#include "src/api/ipc_dbus/IpcDBus.h"

void signalHandler(int signal)
{
    LOG_INFO() << "Received signal:" << signal;
    CoreService* coreService = CoreService::instance();
    if (coreService) {
        coreService->shutdown();
    }

    QCoreApplication::quit();
}

int main(int argc, char *argv[])
{
    // ==================================
    // 创建并配置 Qt 应用程序对象
    // ==================================
    QCoreApplication app(argc, argv);

    app.setApplicationName("soft_bus_daemon");
    app.setApplicationVersion("1.1.0");
    app.setOrganizationName("soft_bus");

    // ==================================
    // 设置 Qt 应用程序信息
    // ==================================
    QCommandLineParser parser;
    parser.setApplicationDescription(QStringLiteral("Soft Bus Daemon"));
    parser.addHelpOption();
    parser.addVersionOption();
    QCommandLineOption roleOption(QStringLiteral("role"),
                                  QStringLiteral("Daemon role (CoreRouter, CollectorSerial, CollectorCan, Collector, SqlServer)"),
                                  QStringLiteral("role"),
                                  QStringLiteral("CoreRouter"));
    parser.addOption(roleOption);
    QCommandLineOption dbusBusOption(QStringLiteral("dbus-bus"),
                                     QStringLiteral("DBus bus to use: system|session|auto (default: auto)"),
                                     QStringLiteral("bus"),
                                     QStringLiteral("auto"));
    parser.addOption(dbusBusOption);
    parser.process(app);


    const QString roleString = parser.value(roleOption).trimmed();
    const QString dbusBus = parser.value(dbusBusOption).trimmed();
    CoreService::Role role = CoreService::Role::CoreRouter; // 默认角色
    if (roleString == QStringLiteral("CoreRouter")) {
        role = CoreService::Role::CoreRouter;
    } else if (roleString == QStringLiteral("CollectorSerial")) {
        role = CoreService::Role::CollectorSerial;
    } else if (roleString == QStringLiteral("CollectorCan")) {
        role = CoreService::Role::CollectorCan;
    } else if (roleString == QStringLiteral("Collector")) {
        role = CoreService::Role::Collector;
    } else if (roleString == QStringLiteral("SqlServer")) {
        role = CoreService::Role::SqlServer;
    } else {
        LOG_ERROR() << "Invalid role:" << roleString
                           << "valid roles are: CoreRouter, CollectorSerial, CollectorCan, Collector, SqlServer";
        return 1;
    }
    // 开启coreserive的初始化工作|线程
    // QThread* coreServiceThread = new QThread();
    // CoreService* coreService = new CoreService();
    // coreService->moveToThread(coreServiceThread);
    // QObject::connect(coreServiceThread, &QThread::started, coreService, &CoreService::initialize);
    // QObject::connect(coreServiceThread, &QThread::finished, coreService, &CoreService::deleteLater);
    // QObject::connect(coreServiceThread, &QThread::finished, coreServiceThread, &QThread::deleteLater);
    // coreServiceThread->start();

    CoreService* coreService = CoreService::instance();
    if (!coreService->initialize()) {
        LOG_ERROR() << "CoreService initialize failed";
        return 1;
    }
    // QObject::connect(&app, &QCoreApplication::aboutToQuit, coreService, &CoreService::shutdown);

    // ========================================================================
    // 创建并注册 D-Bus 服务（仅在 CoreRouter 角色中启用）
    // ========================================================================
    if (role == CoreService::Role::CoreRouter) {
        const QString serviceName = QStringLiteral("com.softbus.Daemon");
        const QString objectPath  = QStringLiteral("/com/softbus/Daemon");

        IpcDBus* ipc = new IpcDBus(coreService, roleString, &app);

        auto pickConnection = [&]() -> QDBusConnection {
            if (dbusBus == QStringLiteral("system")) {
                return QDBusConnection::systemBus();
            }
            if (dbusBus == QStringLiteral("session")) {
                return QDBusConnection::sessionBus();
            }
            // auto: 优先 system（更符合 daemon），失败则退回 session（方便本地开发）
            QDBusConnection conn = QDBusConnection::systemBus();
            if (conn.isConnected()) {
                return conn;
            }
            return QDBusConnection::sessionBus();
        };

        QDBusConnection connection = pickConnection();
        if (!connection.isConnected()) {
            LOG_ERROR() << "Cannot connect to D-Bus. system error="
                        << QDBusConnection::systemBus().lastError().message()
                        << " session error=" << QDBusConnection::sessionBus().lastError().message();
            return 1;
        }

        if (!connection.registerService(serviceName)) {
            LOG_ERROR() << "Failed to register D-Bus service:" << serviceName
                        << "error=" << connection.lastError().message();
            return 1;
        }

        if (!connection.registerObject(objectPath,
                                       ipc,
                                       QDBusConnection::ExportAllSlots | QDBusConnection::ExportAllSignals)) {
            LOG_ERROR() << "Failed to register D-Bus object:" << objectPath
                        << "error=" << connection.lastError().message();
            return 1;
        }

        LOG_INFO() << "D-Bus ready. bus="
                   << (connection.name() == QDBusConnection::systemBus().name() ? "system" : "session")
                   << " service=" << serviceName
                   << " object=" << objectPath;
    }
    


    // ==================================
    //  处理系统信号，确保在接收到 SIGINT 或 SIGTERM 时能够优雅地退出
    // ==================================

    signal(SIGINT, signalHandler);
    signal(SIGTERM, signalHandler);

    int ret = app.exec();
    return ret;
}
