<?php

declare(strict_types=1);

namespace App\Framework\Core;

use RecursiveIteratorIterator;

class DiscoveryCacheManager

{
    private string $baseCachePath;

    public function __construct(?string $baseCachePath = null)
    {
        $this->baseCachePath = $baseCachePath ?? __DIR__ . '/../../../cache';
    }

    public function getCachePathForDirectory(string $directory): string
    {
        $hash = md5(realpath($directory));
        return $this->baseCachePath . "/discovery_{$hash}.cache.php";
    }

    public function loadCache(string $cacheFile, int $latestMTime): ?array
    {
        if (!file_exists($cacheFile)) {
            return null;
        }

        $data = include $cacheFile;
        if (
            !is_array($data)
            || !isset($data['__discovery_mtime'])
            || $data['__discovery_mtime'] !== $latestMTime
        ) {
            return null;
        }

        unset($data['__discovery_mtime']);
        return $data;
    }

    public function storeCache(string $cacheFile, array $results): void
    {
        // Stellen Sie sicher, dass das Verzeichnis existiert
        $cacheDir = dirname($cacheFile);
        if (!is_dir($cacheDir)) {
            mkdir($cacheDir, 0775, true);
        }

        $export = var_export($results, true);
        file_put_contents($cacheFile, "<?php\nreturn {$export};\n");
    }
}
