<?php
declare(strict_types=1);

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

use PpPhp\Core\Platform\Event\Dispatcher\DelayedDispatcher;

final class DispatcherRuntimeManager
{
    private static ?self $instance = null;

    private DelayedDispatcher $dispatcher;
    private DispatcherRuntimeStore $store;

    private function __construct(private readonly string $basePath)
    {
        $this->dispatcher = new DelayedDispatcher();
        $this->store = new DispatcherRuntimeStore($basePath);
    }

    public static function instance(?string $basePath = null): self
    {
        if (self::$instance === null) {
            $basePath ??= self::detectBasePath();
            self::$instance = new self($basePath);
        }

        return self::$instance;
    }

    public static function resetInstance(?string $basePath = null): self
    {
        $basePath ??= self::detectBasePath();
        self::$instance = new self($basePath);
        return self::$instance;
    }

    public function dispatcher(): DelayedDispatcher
    {
        return $this->dispatcher;
    }

    public function store(): DispatcherRuntimeStore
    {
        return $this->store;
    }

    public function consoleState(): DispatcherConsoleStateHydrator
    {
        return new DispatcherConsoleStateHydrator($this);
    }

    public function save(): DispatcherRuntimeState
    {
        return $this->store->save($this->dispatcher);
    }

    public function load(): DispatcherRuntimeState
    {
        return $this->store->load();
    }

    public function clear(): void
    {
        $this->dispatcher->clear();
        $this->store->reset();
    }

    public function summary(): array
    {
        return [
            'statistics' => $this->consoleState()->statistics(),
            'persisted' => $this->store->exists(),
            'stateFile' => $this->store->stateFile(),
            'loadedState' => $this->load()->toArray(),
        ];
    }

    private static function detectBasePath(): string
    {
        $candidate = dirname(__DIR__, 5);
        $real = realpath($candidate);
        return $real !== false ? $real : $candidate;
    }
}
