#include <QApplication>
#include <QFile>
#include <QQuickWindow>  // 关键头文件
#include <QTextStream>

#include "backendapimanager.h"
#include "fireWidget/firingwidget.h"
#include "global.h"
#include "logger.h"
#include "loginwindow.h"
#include "mainwindow.h"
#include "mqtt/mqttclient.h"

int main(int argc, char* argv[]) {
    QApplication app(argc, argv);

    QQuickWindow::setSceneGraphBackend("software");  // 兼容性： 禁用GPU

    // 加载 QSS 文件
    QFile styleFile(":/qss/qss/tableview.qss");
    if (styleFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QTextStream stream(&styleFile);
        QString styleSheet = stream.readAll();
        app.setStyleSheet(styleSheet);
        styleFile.close();
    }

    // logger
    Logger::getInstance("application.log");

    Logger::getInstance().setMaxFileSize(2 * 1024 * 1024);  // 2 MB
    Logger::getInstance().setMaxBackupFiles(3);             // Keep 3 backup files
    Logger::getInstance().info("Application started from main.");

    loadConfig();
    backendAPIManager::initialize(apiBackendUrl.toString());

    // Initialize MQTT client with proper error handling
    try {
        mainMqttClient = new MqttClient();
        if (mainMqttClient != nullptr) {
            mainMqttClient->connectToMqttBroker("114.55.233.194", 1883, "hxgc", "hxgc123456", mqttClientId);
            Logger::getInstance().info("MQTT client initialized successfully");
        } else {
            Logger::getInstance().error("Failed to create MQTT client instance");
        }
    } catch (const std::exception& e) {
        Logger::getInstance().error(QString("Exception while initializing MQTT client: %1").arg(e.what()));
    } catch (...) {
        Logger::getInstance().error("Unknown exception while initializing MQTT client");
    }

    // MainWindow w;
    //  Page w;
    //  pageTest w;
    LoginWindow w;
    // loginWindow.show();
    // 设置应用程序图标
    app.setWindowIcon(QIcon(":/icons/icons/l634z-aceaj-001.ico"));
    // w.resize(screenWidth * 1, screenHeight * 0.95);
    // firingWidget w;
    w.show();
    return app.exec();
}
