// shape_loader.cpp - Implementació del carregador con caché
// © 2026 JailDesigner

#include "core/graphics/shape_loader.hpp"

#include <iostream>

#include "core/resources/resource_helper.hpp"

namespace Graphics {

    // Inicialización de variables estàtiques
    std::unordered_map<std::string, std::shared_ptr<Shape>> ShapeLoader::cache;

    auto ShapeLoader::load(const std::string& filename) -> std::shared_ptr<Shape> {
        // Check cache first
        auto it = cache.find(filename);
        if (it != cache.end()) {
            std::cout << "[ShapeLoader] Cache hit: " << filename << '\n';
            return it->second;  // Cache hit
        }

        // Normalize path: "ship.shp" → "shapes/ship.shp"
        //                 "logo/letra_j.shp" → "shapes/logo/letra_j.shp"
        std::string normalized = filename;
        if (!normalized.starts_with("shapes/")) {
            // Doesn't start with "shapes/", so add it
            normalized = "shapes/" + normalized;
        }

        // Load from resource system
        std::vector<uint8_t> data = Resource::Helper::loadFile(normalized);
        if (data.empty()) {
            std::cerr << "[ShapeLoader] Error: no s'ha pogut load " << normalized
                      << '\n';
            return nullptr;
        }

        // Convert bytes to string and parse
        std::string file_content(data.begin(), data.end());
        auto shape = std::make_shared<Shape>();
        if (!shape->parseFile(file_content)) {
            std::cerr << "[ShapeLoader] Error: no s'ha pogut parsejar " << normalized
                      << '\n';
            return nullptr;
        }

        // Verify shape is valid
        if (!shape->isValid()) {
            std::cerr << "[ShapeLoader] Error: shape invàlida " << normalized << '\n';
            return nullptr;
        }

        // Cache and return
        std::cout << "[ShapeLoader] Carregat: " << normalized << " (" << shape->getName()
                  << ", " << shape->getNumPrimitives() << " primitives)" << '\n';

        cache[filename] = shape;
        return shape;
    }

    void ShapeLoader::clearCache() {
        std::cout << "[ShapeLoader] Netejant caché (" << cache.size() << " formes)"
                  << '\n';
        cache.clear();
    }

    auto ShapeLoader::getCacheSize() -> size_t { return cache.size(); }

}  // namespace Graphics
