#include "gfx/dag_uniforms.h"
#include "gfx/dag_compile.h"
#include "gfx/dag_catalog.h"
#include "gfx/gl_loader.h"
#include <algorithm>
#include <cstring>

namespace fn::gfx {

static constexpr int MAX_PARAM_VEC4S = 64;

void dag_uniforms_apply(const std::vector<DagStep>& pipeline, unsigned int program) {
    float data[MAX_PARAM_VEC4S * 4];
    std::memset(data, 0, sizeof(data));

    std::vector<int> base = dag_param_layout(pipeline);

    for (size_t i = 0; i < pipeline.size(); ++i) {
        const DagStep& step = pipeline[i];
        const DagNodeDef* def = dag_find(step.name);
        if (!def) continue;
        int pc = static_cast<int>(def->param_defaults.size());
        int b  = base[i] * 4;
        for (int k = 0; k < pc && b + k < MAX_PARAM_VEC4S * 4; ++k) {
            data[b + k] = (k < static_cast<int>(step.params.size())) ? step.params[static_cast<size_t>(k)] : 0.0f;
        }
    }

    GLint loc = glGetUniformLocation(program, "u_params");
    if (loc >= 0) glUniform4fv(loc, MAX_PARAM_VEC4S, data);

    // Default render path: ensure preview branch in the compiled DAG shader is
    // disabled (per-node previews override this transiently in dag_previews_render).
    GLint loc_pt = glGetUniformLocation(program, "u_preview_target");
    if (loc_pt >= 0) glUniform1i(loc_pt, -1);
}

} // namespace fn::gfx
