#include "OcioConfigParser.h"

#include <OpenColorIO/OpenColorIO.h>
namespace OCIO = OCIO_NAMESPACE;

namespace UsdLayerManager {

const OcioConfig& GetCurrentOcioConfig() {
    static OcioConfig s_config;
    static bool       s_loaded = false;
    if (s_loaded) return s_config;
    s_loaded = true;

    try {
        OCIO::ConstConfigRcPtr cfg = OCIO::GetCurrentConfig();
        if (!cfg) return s_config;

        // Displays + views per display
        const char* defDisp = cfg->getDefaultDisplay();
        if (defDisp) s_config.defaultDisplay = defDisp;

        int nD = cfg->getNumDisplays();
        for (int i = 0; i < nD; ++i) {
            const char* disp = cfg->getDisplay(i);
            if (!disp) continue;
            s_config.displays.emplace_back(disp);
            auto& viewVec = s_config.views[disp];
            int nV = cfg->getNumViews(disp);
            for (int j = 0; j < nV; ++j) {
                const char* v = cfg->getView(disp, j);
                if (v) viewVec.emplace_back(v);
            }
        }

        if (!s_config.defaultDisplay.empty()) {
            const char* dv = cfg->getDefaultView(s_config.defaultDisplay.c_str());
            if (dv) s_config.defaultView = dv;
        }

        // Color spaces
        int nCS = cfg->getNumColorSpaces();
        for (int i = 0; i < nCS; ++i) {
            const char* cs = cfg->getColorSpaceNameByIndex(i);
            if (cs) s_config.colorSpaces.emplace_back(cs);
        }

        // Looks
        int nL = cfg->getNumLooks();
        for (int i = 0; i < nL; ++i) {
            const char* look = cfg->getLookNameByIndex(i);
            if (look) s_config.looks.emplace_back(look);
        }

        s_config.valid = true;
    } catch (const std::exception&) {
        // OCIO not configured — s_config stays empty with valid=false
    }

    return s_config;
}

} // namespace UsdLayerManager
