#include "ItemRegistry.h"
#include "utils/Utils.h"
#include "external/nlohmann/json.hpp"
#include <iostream>

namespace ZL {

ItemRegistry& ItemRegistry::instance() {
    static ItemRegistry reg;
    return reg;
}

void ItemRegistry::loadFromJson(const std::string& jsonPath, const std::string& zipPath) {
    std::string content;
    try {
        if (zipPath.empty()) {
            content = readTextFile(jsonPath);
        } else {
            auto buf = readFileFromZIP(jsonPath, zipPath);
            if (buf.empty()) {
                std::cerr << "[ItemRegistry] Failed to read " << jsonPath << " from zip\n";
                return;
            }
            content.assign(buf.begin(), buf.end());
        }
    } catch (const std::exception& e) {
        std::cerr << "[ItemRegistry] Failed to open " << jsonPath << ": " << e.what() << "\n";
        return;
    }

    using json = nlohmann::json;
    json j;
    try {
        j = json::parse(content);
    } catch (const std::exception& e) {
        std::cerr << "[ItemRegistry] JSON parse error in " << jsonPath << ": " << e.what() << "\n";
        return;
    }

    if (!j.contains("items") || !j["items"].is_array()) {
        std::cerr << "[ItemRegistry] No 'items' array in " << jsonPath << "\n";
        return;
    }

    items_.clear();

    for (const auto& entry : j["items"]) {
        std::string id = entry.value("id", "");
        if (id.empty()) continue;

        Item item(
            id,
            entry.value("name", "Unknown"),
            entry.value("description", ""),
            entry.value("icon", "")
        );
        items_[id] = std::move(item);
    }

    std::cout << "[ItemRegistry] Loaded " << items_.size() << " items from " << jsonPath << "\n";
}

const Item* ItemRegistry::findById(const std::string& id) const {
    auto it = items_.find(id);
    return it != items_.end() ? &it->second : nullptr;
}

} // namespace ZL
