#include <filesystem>
#include <fstream>
#include <iostream>
#include <chrono>

std::chrono::system_clock::time_point ParseEmbeddedTimestamp(const std::string& timestamp) {
    std::tm tm = {};
    std::istringstream ss(timestamp);
    ss >> std::get_time(&tm, "%Y-%m-%d %H:%M:%S");
    return std::chrono::system_clock::from_time_t(std::mktime(&tm));
}

void WriteUIFileToDiskIfChanged(
    const std::string& filePath,
    const unsigned char* data,
    const size_t length,
    const std::string& lastModified) {

    auto embeddedTimestamp = ParseEmbeddedTimestamp(lastModified);

    if (std::filesystem::exists(filePath)) {
        const auto lastWriteTime = std::filesystem::last_write_time(filePath);

        // Convert file_time_type to system_clock::time_point
        const auto lastWriteTimeTp = std::chrono::time_point_cast<std::chrono::system_clock::duration>(
            lastWriteTime - std::filesystem::file_time_type::clock::now() + std::chrono::system_clock::now()
        );

        if (lastWriteTimeTp < embeddedTimestamp) {
            std::ofstream file(filePath, std::ios::binary);
            file.write(reinterpret_cast<const char*>(data), length);
        }
    } else {
        std::ofstream file(filePath, std::ios::binary);
        file.write(reinterpret_cast<const char*>(data), length);
    }
}
