<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Event\Distributed;

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

    private DistributedWorkerRegistry $registry;
    private DistributedRuntimeStore $store;

    private function __construct(private readonly string $basePath)
    {
        $this->registry = new DistributedWorkerRegistry();
        $this->store = new DistributedRuntimeStore($basePath);
        $this->hydrate();
    }

    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 registerWorker(string $workerId, ?string $nodeId = null, int $capacity = 1): DistributedWorkerRecord
    {
        $nodeId ??= DistributedNodeId::generate()->value();
        $record = DistributedWorkerRecord::register($nodeId, $workerId, DistributedWorkerRecord::IDLE, $capacity);

        $this->registry->register($record);
        $this->save();

        return $record;
    }

    public function heartbeat(string $nodeId, string $workerId, string $status = DistributedWorkerRecord::IDLE, int $activeJobs = 0): bool
    {
        $ok = $this->registry->heartbeat($nodeId, $workerId, $status, $activeJobs);
        $this->save();

        return $ok;
    }

    public function registry(): DistributedWorkerRegistry
    {
        return $this->registry;
    }

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

    public function hydrate(): void
    {
        $snapshot = $this->store->load();

        if ($snapshot->workers() !== []) {
            $this->registry = DistributedWorkerRegistry::fromArray($snapshot->workers());
        }
    }

    public function snapshot(): DistributedRuntimeSnapshot
    {
        return new DistributedRuntimeSnapshot($this->registry->toArray(), $this->registry->statistics(), date('c'));
    }

    public function save(): DistributedRuntimeSnapshot
    {
        return $this->store->save($this->snapshot());
    }

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

    public function summary(): array
    {
        $snapshot = $this->snapshot();

        return [
            'workers' => $snapshot->workers(),
            'statistics' => $snapshot->statistics(),
            'persisted' => $this->store->exists(),
            'stateFile' => $this->store->stateFile(),
        ];
    }

    private static function detectBasePath(): string
    {
        $candidate = dirname(__DIR__, 4);
        $real = realpath($candidate);

        return $real !== false ? $real : $candidate;
    }
}
