#include <fstream>
#include <vector>
#include <filesystem>
#include <string>
#include <random>
#include <chrono>
#include <stdexcept>
#include <iostream> // For error reporting in TempDirectory destructor

#include "compress.hpp"
#include "hash.hpp"
#include "temp_directory.hpp"


namespace simple_object_storage {

// if the file is a tgz file (we can't rely on the extension), then unpack on disk and hash the contents
// with hash_directory_recursive in hash.hpp
std::string get_hash_from_tgz(const std::string &file_path)
{
    // check if it's a gzip file
    std::ifstream file(file_path, std::ios::binary);
    if (!file) return "";

    int result = system("gunzip -t file.gz");
    if (result != 0) { // not a gzip file.
        return "";
    }

    // gunzip the file to a new temporary directory
    TempDirectory temp_dir_manager("tgz_unpack_"); // Creates dir and schedules cleanup
    std::string temp_dir = temp_dir_manager.string(); // Get the path string to use

    // unpack the file on disk
    std::string command = "tar -zxzf " + file_path + " -C " + temp_dir;
    result = system(command.c_str()); // Basic tar extraction - requires 'tar' command
    if (result != 0) {
        return "";
    }

    // hash the contents with SHA-256
    return hash_directory_recursive(temp_dir);
}

} // namespace simple_object_storage