#include "platform_api/asset_file_load_policy.h"

#include <string>
#include <sys/stat.h>

namespace pp::platform {

AssetFileTimestampProbe probe_asset_file_timestamp(std::string_view absolute_path)
{
    struct stat file_info {};
    const std::string path(absolute_path);
    if (stat(path.c_str(), &file_info) != 0)
        return {};

    return {
        true,
        static_cast<std::int64_t>(file_info.st_mtime),
    };
}

AssetFileLoadDecision plan_asset_file_load_with_probe(
    PlatformFamily family,
    bool already_loaded,
    std::int64_t previous_last_write_time,
    AssetFileTimestampProbe probe) noexcept
{
    if (platform_uses_asset_file_mtime_reload(family))
    {
        if (!probe.file_exists)
            return { false, false, previous_last_write_time };

        if (probe.last_write_time <= previous_last_write_time)
            return { false, false, previous_last_write_time };

        return { true, true, probe.last_write_time };
    }

    if (already_loaded)
        return { false, true, previous_last_write_time };

    return { true, true, previous_last_write_time };
}

AssetFileLoadDecision plan_asset_file_load_for_platform(
    PlatformFamily family,
    std::string_view absolute_path,
    bool already_loaded,
    std::int64_t previous_last_write_time)
{
    if (!platform_uses_asset_file_mtime_reload(family))
    {
        return plan_asset_file_load_with_probe(
            family,
            already_loaded,
            previous_last_write_time,
            {});
    }

    return plan_asset_file_load_with_probe(
        family,
        already_loaded,
        previous_last_write_time,
        probe_asset_file_timestamp(absolute_path));
}

AssetFileLoadDecision plan_asset_file_load(
    std::string_view absolute_path,
    bool already_loaded,
    std::int64_t previous_last_write_time)
{
    return plan_asset_file_load_for_platform(
        current_platform_family(),
        absolute_path,
        already_loaded,
        previous_last_write_time);
}

}
