/*
 * Tux Manager - Linux system monitor
 * Copyright (C) 2026 Petr Bena <petr@bena.rocks>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

#include "mainwindow.h"
#include "configuration.h"
#include "logger.h"
#include "globals.h"

#include <QApplication>
#include <QCommandLineParser>
#include <QCommandLineOption>
#include <QIcon>
#include <cstdio>
#include <cstring>

// Pre-screen --help / --version before QApplication so they work without a display.
static void print_version()
{
    printf("%s %s\n", TUX_MANAGER_PRODUCT_NAME, TUX_MANAGER_VERSION_STRING);
}

static void print_help()
{
    printf("Usage: %s [options]\n\n"
           "Linux system monitor inspired by Windows Task Manager.\n\n"
           "Options:\n"
           "  -h, --help     Show this help and exit\n"
           "  -V, --version  Show version and exit\n"
           "      --force-drm Force DRM GPU backend and skip NVML detection\n"
           "  -v             Increase log verbosity.\n"
           "                 Repeat for more detail: -v, -vv, -vvv\n",
           TUX_MANAGER_PRODUCT_NAME);
}

int main(int argc, char *argv[])
{
    // Handle --help / --version before constructing QApplication so they
    // are usable from a terminal without a display server present.
    for (int i = 1; i < argc; ++i)
    {
        if (strcmp(argv[i], "--help") == 0 || strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "-?") == 0)
        {
            print_help();
            return 0;
        }
        if (strcmp(argv[i], "--version") == 0 || strcmp(argv[i], "-V") == 0)
        {
            print_version();
            return 0;
        }
    }

    QApplication a(argc, argv);
    a.setOrganizationName(TUX_MANAGER_PRODUCT_NAME);
    a.setApplicationName(TUX_MANAGER_PRODUCT_NAME);
    a.setApplicationVersion(TUX_MANAGER_VERSION_STRING);
    a.setWindowIcon(QIcon(":/tux_manager_256.ico"));

    // ── Command-line parsing (remaining options) ──────────────────────────────
    QCommandLineParser parser;
    parser.setApplicationDescription("Linux system monitor inspired by Windows Task Manager.");
    parser.addHelpOption();

    QCommandLineOption versionOption(QStringList{"V", "version"}, "Display version information and exit.");
    parser.addOption(versionOption);

    QCommandLineOption verboseOption(QStringList{"v"}, "Increase verbosity. Repeat for more detail: -v, -vv, -vvv.");
    parser.addOption(verboseOption);
    QCommandLineOption forceDrmOption(QStringList{"force-drm"}, "Force DRM GPU backend and skip NVML detection.");
    parser.addOption(forceDrmOption);

    parser.process(a);

    // Count -v occurrences manually: handles -v, -vv, -vvv and mixed forms.
    // QCommandLineParser doesn't expose a count() in all Qt versions.
    int verbosity = 0;
    for (const QString &arg : a.arguments().mid(1))
    {
        if (arg.startsWith("--")) continue;
        if (arg.startsWith('-'))
        {
            for (const QChar c : arg.mid(1))
                if (c == 'v') verbosity++;
        }
    }
    Logger::instance()->Verbosity = verbosity;

    // ── Bootstrap ─────────────────────────────────────────────────────────────
    CFG->Load();
    CFG->ForceGpuDrm = parser.isSet(forceDrmOption);
    LOG_INFO(QString("%1 %2 starting (verbosity=%3)").arg(a.applicationName(), a.applicationVersion()).arg(verbosity));

    MainWindow w;
    w.show();
    return a.exec();
}
