#pragma once
#include <vector>
#include <string>
#include <cstdint>

#include <godot_cpp/classes/ref_counted.hpp>
#include <godot_cpp/variant/dictionary.hpp>
#include <godot_cpp/variant/string.hpp>

#include "wow_chunk_reader.h"

namespace godot {

// ─────────────────────────────────────────────────────────────────────────────
// M2Loader
//
// Loads WoW 3.3.5a .m2 model files (raw format, starts with MD20 magic).
// Parses the first skin file (<basename>00.skin) for render geometry.
//
// Usage (GDScript):
//   var loader = M2Loader.new()
//   var data = loader.load_m2("C:/wow/extracted/World/Doodad/Gnome/Gnome.m2")
//
// Return Dictionary:
//   {
//     "textures":       PackedStringArray,   # .blp texture paths (may be empty for replaceable)
//     "texture_types":  PackedInt32Array,    # M2Texture.type per texture slot
//     "texture_flags":  PackedInt32Array,    # M2Texture.flags per texture slot
//     "materials":      Array[Dictionary],   # [{flags, blend_mode}]
//     "texture_combos": PackedInt32Array,    # textureCombos[i] = index into textures
//     "texture_coord_combos":    PackedInt32Array,
//     "texture_combiner_combos": PackedInt32Array,
//     "m2_flags":       int,
//     "model_path":     String,              # absolute source .m2 path
//     "vertices":       PackedVector3Array,  # Godot-space positions
//     "normals":        PackedVector3Array,
//     "uvs":            PackedVector2Array,
//     "uvs2":           PackedVector2Array,
//     "indices":        PackedInt32Array,    # flat triangle list into vertex array
//     "batches":        Array[Dictionary],   # render batches
//   }
//
// Each batch Dictionary:
//   {
//     "index_start":        int,   # offset into indices array
//     "index_count":        int,   # number of indices for this batch
//     "material_id":        int,   # index into materials
//     "texture_count":       int,
//     "shader_id":           int,
//     "texture_coord_combo_index": int,
//     "texture_combo_index": int,  # index into texture_combos → texture
//   }
// ─────────────────────────────────────────────────────────────────────────────
class M2Loader : public RefCounted {
    GDCLASS(M2Loader, RefCounted)

public:
    Dictionary load_m2(const String &path);
    Dictionary load_m2_animated(const String &path);

protected:
    static void _bind_methods();

private:
    Dictionary parse_m2(const std::vector<uint8_t> &buf, const std::string &path, bool include_animation);

    static std::vector<uint8_t> read_file(const std::string &path);
    static std::string          to_std(const String &s);
    static String               to_godot(const std::string &s);
};

} // namespace godot
