#include "hash.hpp"

#include <openssl/sha.h>
#include <fstream>
#include <filesystem>
#include <iostream>
#include <iomanip>
#include <sstream>
#include <vector>
#include <chrono>

namespace simple_object_storage {

// Convert binary hash to hex string
static std::string to_hex_string(const unsigned char* hash, size_t length) {
    std::stringstream ss;
    ss << std::hex << std::setfill('0');
    for (size_t i = 0; i < length; ++i) {
        ss << std::setw(2) << static_cast<unsigned int>(hash[i]);
    }
    return ss.str();
}

std::string hash_file(const std::string &path) {
    // Create SHA256 context
    SHA256_CTX sha256;
    if (!SHA256_Init(&sha256)) {
        std::cerr << "Failed to initialize SHA256" << std::endl;
        return "";
    }

    // Open file
    std::ifstream file(path, std::ios::binary);
    if (!file.is_open()) {
        std::cerr << "Failed to open file: " << path << std::endl;
        return "";
    }

    // Read file in chunks and update hash
    const size_t buffer_size = 8192;
    std::vector<char> buffer(buffer_size);
    
    while (file.read(buffer.data(), buffer_size)) {
        if (!SHA256_Update(&sha256, buffer.data(), file.gcount())) {
            std::cerr << "Failed to update hash" << std::endl;
            return "";
        }
    }

    // Handle any remaining bytes
    if (file.gcount() > 0) {
        if (!SHA256_Update(&sha256, buffer.data(), file.gcount())) {
            std::cerr << "Failed to update hash" << std::endl;
            return "";
        }
    }

    file.close();

    // Get final hash
    unsigned char hash[SHA256_DIGEST_LENGTH];
    if (!SHA256_Final(hash, &sha256)) {
        std::cerr << "Failed to finalize hash" << std::endl;
        return "";
    }

    // Convert to hex string
    return to_hex_string(hash, SHA256_DIGEST_LENGTH);
}

std::string hash_directory_recursive(const std::string &path) {
    // Create SHA256 context for combining hashes
    SHA256_CTX sha256;
    if (!SHA256_Init(&sha256)) {
        std::cerr << "Failed to initialize SHA256" << std::endl;
        return "";
    }

    try {
        // Collect all file paths and sort them for consistent hashing
        std::vector<std::filesystem::path> file_paths;
        for (const auto& entry : std::filesystem::recursive_directory_iterator(path)) {
            if (entry.is_regular_file()) {
                file_paths.push_back(entry.path());
            }
        }
        
        // Sort paths for deterministic hashing
        std::sort(file_paths.begin(), file_paths.end());
        
        // Hash each file and combine
        for (const auto& file_path : file_paths) {
            // Get file hash
            std::string file_hash_str = hash_file(file_path.string());
            if (file_hash_str.empty()) {
                std::cerr << "Failed to hash file: " << file_path << std::endl;
                continue;
            }
            
            // Update combined hash with file hash and path
            std::string relative_path = std::filesystem::relative(file_path, path).string();
            SHA256_Update(&sha256, relative_path.c_str(), relative_path.length());
            SHA256_Update(&sha256, file_hash_str.c_str(), file_hash_str.length());
        }
    } catch (const std::filesystem::filesystem_error& e) {
        std::cerr << "Filesystem error: " << e.what() << std::endl;
        return "";
    }

    // Get final combined hash
    unsigned char hash[SHA256_DIGEST_LENGTH];
    if (!SHA256_Final(hash, &sha256)) {
        std::cerr << "Failed to finalize hash" << std::endl;
        return "";
    }

    // Convert to hex string
    return to_hex_string(hash, SHA256_DIGEST_LENGTH);
}

void hash_demo(const std::string & path) {
    std::cout << "Hashing directory: " << path << std::endl;
    auto start = std::chrono::high_resolution_clock::now();
    std::string hash = hash_directory_recursive(path);
    auto end = std::chrono::high_resolution_clock::now();
    auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
    std::cout << "SHA-256 Hash: " << hash << " (took " << duration.count() << "ms)" << std::endl;
}

int hash_demo_raw(const std::string & path) {
    if (!std::filesystem::exists(path)) {
        std::cout << "0" << std::endl; 
        return 1;
    }
    std::string hash = hash_directory_recursive(path);
    std::cout << hash << std::endl;
    return 0;
}

} // namespace simple_object_storage