#include "core/resources/resource_pack.h"

#include <algorithm>
#include <array>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <numeric>
#include <utility>

const std::string ResourcePack::DEFAULT_ENCRYPT_KEY = "CCRS_RESOURCES__2026";

ResourcePack::ResourcePack()
    : loaded_(false) {}

ResourcePack::~ResourcePack() {
    clear();
}

uint32_t ResourcePack::calculateChecksum(const std::vector<uint8_t>& data) {
    return std::accumulate(data.begin(), data.end(), uint32_t(0x12345678), [](uint32_t acc, uint8_t b) { return ((acc << 5) + acc) + b; });
}

void ResourcePack::encryptData(std::vector<uint8_t>& data, const std::string& key) {
    if (key.empty()) return;
    for (size_t i = 0; i < data.size(); ++i) {
        data[i] ^= key[i % key.length()];
    }
}

void ResourcePack::decryptData(std::vector<uint8_t>& data, const std::string& key) {
    encryptData(data, key);
}

bool ResourcePack::loadPack(const std::string& pack_file) {
    std::ifstream file(pack_file, std::ios::binary);
    if (!file) {
        std::cerr << "Error: Could not open pack file: " << pack_file << '\n';
        return false;
    }

    std::array<char, 4> header;
    file.read(header.data(), 4);
    if (std::string(header.data(), 4) != "CCRS") {
        std::cerr << "Error: Invalid pack file format" << '\n';
        return false;
    }

    uint32_t version;
    file.read(reinterpret_cast<char*>(&version), sizeof(version));
    if (version != 1) {
        std::cerr << "Error: Unsupported pack version: " << version << '\n';
        return false;
    }

    uint32_t resource_count;
    file.read(reinterpret_cast<char*>(&resource_count), sizeof(resource_count));

    resources_.clear();
    resources_.reserve(resource_count);

    for (uint32_t i = 0; i < resource_count; ++i) {
        uint32_t filename_length;
        file.read(reinterpret_cast<char*>(&filename_length), sizeof(filename_length));

        std::string filename(filename_length, '\0');
        file.read(filename.data(), filename_length);

        ResourceEntry entry;
        entry.filename = filename;
        file.read(reinterpret_cast<char*>(&entry.offset), sizeof(entry.offset));
        file.read(reinterpret_cast<char*>(&entry.size), sizeof(entry.size));
        file.read(reinterpret_cast<char*>(&entry.checksum), sizeof(entry.checksum));

        resources_[filename] = entry;
    }

    uint64_t data_size;
    file.read(reinterpret_cast<char*>(&data_size), sizeof(data_size));

    data_.resize(data_size);
    file.read(reinterpret_cast<char*>(data_.data()), data_size);

    decryptData(data_, DEFAULT_ENCRYPT_KEY);

    loaded_ = true;
    return true;
}

bool ResourcePack::savePack(const std::string& pack_file) {
    std::ofstream file(pack_file, std::ios::binary);
    if (!file) {
        std::cerr << "Error: Could not create pack file: " << pack_file << '\n';
        return false;
    }

    file.write("CCRS", 4);

    uint32_t version = 1;
    file.write(reinterpret_cast<const char*>(&version), sizeof(version));

    uint32_t resource_count = static_cast<uint32_t>(resources_.size());
    file.write(reinterpret_cast<const char*>(&resource_count), sizeof(resource_count));

    for (const auto& [filename, entry] : resources_) {
        uint32_t filename_length = static_cast<uint32_t>(filename.length());
        file.write(reinterpret_cast<const char*>(&filename_length), sizeof(filename_length));
        file.write(filename.c_str(), filename_length);

        file.write(reinterpret_cast<const char*>(&entry.offset), sizeof(entry.offset));
        file.write(reinterpret_cast<const char*>(&entry.size), sizeof(entry.size));
        file.write(reinterpret_cast<const char*>(&entry.checksum), sizeof(entry.checksum));
    }

    std::vector<uint8_t> encrypted_data = data_;
    encryptData(encrypted_data, DEFAULT_ENCRYPT_KEY);

    uint64_t data_size = encrypted_data.size();
    file.write(reinterpret_cast<const char*>(&data_size), sizeof(data_size));
    file.write(reinterpret_cast<const char*>(encrypted_data.data()), data_size);

    return true;
}

bool ResourcePack::addFile(const std::string& filename, const std::string& filepath) {
    std::ifstream file(filepath, std::ios::binary | std::ios::ate);
    if (!file) {
        std::cerr << "Error: Could not open file: " << filepath << '\n';
        return false;
    }

    std::streamsize file_size = file.tellg();
    file.seekg(0, std::ios::beg);

    std::vector<uint8_t> file_data(file_size);
    if (!file.read(reinterpret_cast<char*>(file_data.data()), file_size)) {
        std::cerr << "Error: Could not read file: " << filepath << '\n';
        return false;
    }

    ResourceEntry entry;
    entry.filename = filename;
    entry.offset = data_.size();
    entry.size = file_data.size();
    entry.checksum = calculateChecksum(file_data);

    data_.insert(data_.end(), file_data.begin(), file_data.end());
    resources_[filename] = entry;

    return true;
}

bool ResourcePack::addDirectory(const std::string& directory) {
    if (!std::filesystem::exists(directory)) {
        std::cerr << "Error: Directory does not exist: " << directory << '\n';
        return false;
    }

    // cppcheck-suppress useStlAlgorithm
    for (const auto& entry : std::filesystem::recursive_directory_iterator(directory)) {
        if (entry.is_regular_file()) {
            std::string filepath = entry.path().string();
            std::string filename = std::filesystem::relative(entry.path(), directory).string();

            std::replace(filename.begin(), filename.end(), '\\', '/');

            if (!addFile(filename, filepath)) {
                return false;
            }
        }
    }

    return true;
}

std::vector<uint8_t> ResourcePack::getResource(const std::string& filename) {
    auto it = resources_.find(filename);
    if (it == resources_.end()) {
        std::cerr << "Error: Resource not found: " << filename << '\n';
        return {};
    }

    const ResourceEntry& entry = it->second;
    if (entry.offset + entry.size > data_.size()) {
        std::cerr << "Error: Invalid resource data: " << filename << '\n';
        return {};
    }

    std::vector<uint8_t> result(data_.begin() + entry.offset,
        data_.begin() + entry.offset + entry.size);

    uint32_t checksum = calculateChecksum(result);
    if (checksum != entry.checksum) {
        std::cerr << "Warning: Checksum mismatch for resource: " << filename << '\n';
    }

    return result;
}

bool ResourcePack::hasResource(const std::string& filename) const {
    return resources_.find(filename) != resources_.end();
}

void ResourcePack::clear() {
    resources_.clear();
    data_.clear();
    loaded_ = false;
}

size_t ResourcePack::getResourceCount() const {
    return resources_.size();
}

std::vector<std::string> ResourcePack::getResourceList() const {
    std::vector<std::string> result;
    result.reserve(resources_.size());
    for (const auto& [filename, entry] : resources_) {
        result.push_back(filename);
    }
    return result;
}
