#include "ThemeConfig.h"
#include <QFile>
#include <QJsonDocument>
#include <QJsonObject>
#include <QStandardPaths>
#include <QDir>

// No-op parser retained for forward compatibility; currently no fields to apply
static void applyJson(const QJsonObject &, ThemeConfig &) {}

QString ThemeConfig::locateUserConfig() {
    const QByteArray env = qgetenv("BIANBU_THEME_FILE");
    if (!env.isEmpty() && QFile::exists(QString::fromLocal8Bit(env)))
        return QString::fromLocal8Bit(env);

    // Use ConfigLocation to allow per-app; fallback to plain config dir
    const QString cfgLoc = QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation);
    if (!cfgLoc.isEmpty()) {
        QString candidate = cfgLoc + "/bianbu/theme.json";
        if (QFile::exists(candidate)) return candidate;
    }
    // Generic global config (~/.config)
    const QString genCfg = QStandardPaths::writableLocation(QStandardPaths::ConfigLocation);
    if (!genCfg.isEmpty()) {
        QString candidate = genCfg + "/bianbu/theme.json";
        if (QFile::exists(candidate)) return candidate;
    }
    // Data locations (user override installed)
    const QStringList dataDirs = QStandardPaths::standardLocations(QStandardPaths::GenericDataLocation);
    for (const QString &d : dataDirs) {
        QString candidate = d + "/bianbu/theme.json";
        if (QFile::exists(candidate)) return candidate;
    }
    return {};
}


ThemeConfig ThemeConfig::load(const QString &explicitPath) {
    ThemeConfig cfg;
    QString path = explicitPath;
    if (path.isEmpty()) path = ThemeConfig::locateUserConfig();

    auto loadFromFile = [&](const QString &filePath){
        QFile f(filePath);
        if (!f.open(QIODevice::ReadOnly)) return;
        const auto doc = QJsonDocument::fromJson(f.readAll());
        if (!doc.isObject()) return;
        applyJson(doc.object(), cfg);
    };

    if (!path.isEmpty()) {
        loadFromFile(path);
        return cfg;
    }

    // Locate installed default: prefer data dir, then local relative (developer build)
    QString defaultPath = QStandardPaths::locate(QStandardPaths::GenericDataLocation, QStringLiteral("bianbu/default-theme.json"));
    if (defaultPath.isEmpty() && QFile::exists(QStringLiteral("default-theme.json"))) {
        defaultPath = QStringLiteral("default-theme.json");
    }
    if (!defaultPath.isEmpty()) loadFromFile(defaultPath);
    return cfg;
}
