<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Event\Worker\Runtime;

use PpPhp\Core\Platform\Event\Worker\WorkerRuntime;

final class WorkerRuntimeStore
{
    public const CACHE_DIR = 'storage/cache/events/workers';
    public const STATE_FILE = 'worker-runtime.json';

    public function __construct(private readonly string $basePath, private readonly WorkerRuntimeSerializer $serializer = new WorkerRuntimeSerializer()) {}

    public function stateFile(): string
    {
        return rtrim($this->basePath, DIRECTORY_SEPARATOR) . '/' . self::CACHE_DIR . '/' . self::STATE_FILE;
    }

    public function save(WorkerRuntime $runtime): WorkerRuntimeState
    {
        $summary = $runtime->summary();
        $state = new WorkerRuntimeState((array) ($summary['workers'] ?? []), (array) ($summary['statistics'] ?? []), (array) ($summary['lifecycle'] ?? []), date('c'));

        $file = $this->stateFile();
        if (!is_dir(dirname($file))) {
            mkdir(dirname($file), 0775, true);
        }
        file_put_contents($file, $this->serializer->encode($state));

        return $state;
    }

    public function load(): WorkerRuntimeState
    {
        $file = $this->stateFile();
        if (!is_file($file)) {
            return new WorkerRuntimeState();
        }
        return $this->serializer->decode((string) file_get_contents($file));
    }

    public function reset(): void
    {
        $file = $this->stateFile();
        if (is_file($file)) {
            unlink($file);
        }
    }

    public function exists(): bool
    {
        return is_file($this->stateFile());
    }
}
