#include "compiler.h"

#include "gfx/shader_canvas.h"
#include "gfx/gl_shader.h"
#include "gfx/uniform_parser.h"
#include "gfx/uniform_panel.h"
#include "gfx/dag_compile.h"
#include "gfx/dag_uniforms.h"

#include <chrono>
#include <string>
#include <vector>

// ── Globals declarados en main.cpp (single source of truth) ─────────────────
extern fn::gfx::ShaderCanvas                     g_canvas_code;
extern fn::gfx::ShaderCanvas                     g_canvas_dag;
extern std::string                               g_source;
extern std::string                               g_code_err;
extern int                                       g_code_err_line;
extern std::chrono::steady_clock::time_point     g_code_last_edit;
extern bool                                      g_code_dirty;
extern std::vector<fn::gfx::UniformDescriptor>   g_descs;
extern fn::gfx::UniformStore                     g_store;
extern std::vector<fn::gfx::DagStep>             g_pipeline;
extern std::string                               g_dag_glsl;
extern std::string                               g_dag_err;
extern int                                       g_dag_err_line;

namespace shaders_lab {

void compile_code() {
    auto r = fn::gfx::compile_fragment(g_source);
    if (r.ok) {
        g_descs = fn::gfx::parse_uniforms(g_source);
        fn::gfx::uniforms_sync(g_store, g_descs);
        fn::gfx::canvas_set_program(g_canvas_code, r.program);
        g_code_err.clear();
        g_code_err_line = -1;
    } else {
        g_code_err      = r.err_msg;
        g_code_err_line = r.err_line;
    }
}

void compile_dag() {
    g_dag_glsl = fn::gfx::compile_dag_to_glsl(g_pipeline);
    auto r = fn::gfx::compile_fragment(g_dag_glsl);
    if (r.ok) {
        fn::gfx::canvas_set_program(g_canvas_dag, r.program);
        g_dag_err.clear();
        g_dag_err_line = -1;
    } else {
        g_dag_err      = r.err_msg;
        g_dag_err_line = r.err_line;
    }
}

void mark_code_dirty() {
    g_code_last_edit = std::chrono::steady_clock::now();
    g_code_dirty     = true;
}

} // namespace shaders_lab
