<?php
declare(strict_types=1);

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

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

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

    private WorkerRuntime $runtime;
    private WorkerRuntimeStore $store;

    private function __construct(private readonly string $basePath)
    {
        $this->runtime = new WorkerRuntime();
        $this->store = new WorkerRuntimeStore($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 runtime(): WorkerRuntime { return $this->runtime; }
    public function store(): WorkerRuntimeStore { return $this->store; }
    public function consoleState(): WorkerConsoleStateHydrator { return new WorkerConsoleStateHydrator($this); }

    public function ensureDefaultWorker(string $id = 'worker_console'): void
    {
        if ($this->runtime->workers()->count() === 0) {
            $this->runtime->register(new DispatcherWorkerAdapter($id));
        }
    }

    public function save(): WorkerRuntimeState { return $this->store->save($this->runtime); }
    public function load(): WorkerRuntimeState { return $this->store->load(); }

    public function clear(): void
    {
        $this->runtime = new WorkerRuntime();
        $this->store->reset();
    }

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

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