// SPDX-License-Identifier: MIT
// mvgal_spirv_cross.cpp — SPIRV-Cross decompiler wrapper (Phase 2)

#include "mvgal_shader_translate.h"

#include <cstdlib>
#include <cstring>

#include "spirv_cross_c.h"

extern "C" char *mvgal_spirv_decompile(const uint32_t *spirv,
                                       size_t word_count,
                                       mvgal_spirv_backend_t backend) {
    if (!spirv || word_count == 0) return nullptr;

    spvc_backend b;
    switch (backend) {
    case MVGAL_SPIRV_BACKEND_GLSL: b = SPVC_BACKEND_GLSL; break;
    case MVGAL_SPIRV_BACKEND_HLSL: b = SPVC_BACKEND_HLSL; break;
    case MVGAL_SPIRV_BACKEND_MSL:  b = SPVC_BACKEND_MSL;  break;
    default: return nullptr;
    }

    spvc_context ctx = nullptr;
    if (spvc_context_create(&ctx) != SPVC_SUCCESS)
        return nullptr;

    spvc_parsed_ir ir = nullptr;
    if (spvc_context_parse_spirv(ctx, spirv, word_count, &ir) != SPVC_SUCCESS) {
        spvc_context_destroy(ctx);
        return nullptr;
    }

    spvc_compiler comp = nullptr;
    if (spvc_context_create_compiler(ctx, b, ir, SPVC_CAPTURE_MODE_TAKE_OWNERSHIP, &comp) != SPVC_SUCCESS) {
        spvc_context_destroy(ctx);
        return nullptr;
    }

    // Install default options for the selected backend
    spvc_compiler_options opts = nullptr;
    if (spvc_compiler_create_compiler_options(comp, &opts) == SPVC_SUCCESS) {
        spvc_compiler_options_set_bool(opts, SPVC_COMPILER_OPTION_FLATTEN_MULTIDIMENSIONAL_ARRAYS, true);
        if (b == SPVC_BACKEND_GLSL)
            spvc_compiler_options_set_uint(opts, SPVC_COMPILER_OPTION_GLSL_VERSION, 460);
        spvc_compiler_install_compiler_options(comp, opts);
    }

    const char *source = nullptr;
    char *result = nullptr;
    if (spvc_compiler_compile(comp, &source) == SPVC_SUCCESS && source)
        result = strdup(source);

    spvc_context_destroy(ctx);
    return result;
}
