<?php
declare(strict_types=1);

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

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

    private WorkerHealthStore $store;
    private WorkerHealthMonitor $monitor;

    private function __construct(private readonly string $basePath)
    {
        $this->store = new WorkerHealthStore($basePath);
        $this->monitor = new WorkerHealthMonitor();
    }

    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 inspect(?WorkerHeartbeatCollection $heartbeats = null): WorkerHealthSnapshot
    {
        if ($heartbeats === null) {
            $heartbeatManager = WorkerHeartbeatManager::instance($this->basePath);
            $heartbeatManager->hydrate();
            $heartbeats = $heartbeatManager->collection();
        }

        $snapshot = $this->monitor->inspect($heartbeats);
        $this->store->save($snapshot);

        return $snapshot;
    }

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

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

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

    public function summary(): array
    {
        $snapshot = $this->store->exists() ? $this->load() : $this->inspect();

        return [
            'records' => $snapshot->records(),
            'statistics' => $snapshot->statistics(),
            '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;
    }
}
