<?php
/**
 * Caché de estadísticas de carpetas del explorador (tamaño recursivo) para
 * no volver a recorrer el árbol en cada apertura del panel de configuración.
 */

if (!defined('EXPLORER_STORAGE_STATS_CACHE_TTL')) {
    define('EXPLORER_STORAGE_STATS_CACHE_TTL', 300);
}
if (!defined('EXPLORER_STORAGE_STATS_CACHE_NAME')) {
    define('EXPLORER_STORAGE_STATS_CACHE_NAME', 'explorer_storage_stats.v1.json');
}

/**
 * Ruta al archivo de caché bajo temp/ del proyecto.
 */
function grid_explorer_storage_cache_path(): string
{
    $d = (defined('GRID_ROOT') ? GRID_ROOT : dirname(__DIR__)) . '/temp';
    if (!is_dir($d)) {
        @mkdir($d, 0755, true);
    }

    return $d . DIRECTORY_SEPARATOR . EXPLORER_STORAGE_STATS_CACHE_NAME;
}

/**
 * @return null|array{ t:int, remoteCache: array, trash: array, files: array }
 */
function grid_explorer_storage_cache_read()
{
    $f = grid_explorer_storage_cache_path();
    if (!is_file($f)) {
        return null;
    }
    $raw = @file_get_contents($f);
    if ($raw === false || $raw === '') {
        return null;
    }
    $d = @json_decode($raw, true);
    if (!is_array($d) || !isset($d['t'], $d['remoteCache'], $d['trash'], $d['files']) || (int) $d['t'] < 1) {
        return null;
    }
    if (!is_array($d['remoteCache']) || !is_array($d['trash']) || !is_array($d['files'])) {
        return null;
    }

    return $d;
}

/**
 * Caché válida si el archivo existe y t no excede TTL.
 */
function grid_explorer_storage_cache_fresh(int $ttl = EXPLORER_STORAGE_STATS_CACHE_TTL): ?array
{
    $c = grid_explorer_storage_cache_read();
    if ($c === null) {
        return null;
    }
    if ((time() - (int) $c['t']) > $ttl) {
        return null;
    }

    return $c;
}

/**
 * @param array{ bytes:int, files:int } $rc
 * @param array{ bytes:int, files:int } $tr
 * @param array{ bytes:int, files:int } $fl
 */
function grid_explorer_storage_cache_write(array $rc, array $tr, array $fl, ?int $timestamp = null): void
{
    $path = grid_explorer_storage_cache_path();
    $payload = [
        't' => $timestamp !== null ? (int) $timestamp : time(),
        'v' => 1,
        'remoteCache' => $rc,
        'trash' => $tr,
        'files' => $fl,
    ];
    $dir = dirname($path);
    if (!is_dir($dir)) {
        @mkdir($dir, 0755, true);
    }
    $tmp = $path . '.tmp';
    if (@file_put_contents($tmp, json_encode($payload, JSON_UNESCAPED_UNICODE)) === false) {
        return;
    }
    if (!@rename($tmp, $path) && is_file($tmp)) {
        @copy($tmp, $path);
        @unlink($tmp);
    }
}

function grid_explorer_storage_cache_invalidate(): void
{
    $f = grid_explorer_storage_cache_path();
    if (is_file($f)) {
        @unlink($f);
    }
    $t = $f . '.tmp';
    if (is_file($t)) {
        @unlink($t);
    }
}
