<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Event\Consumer\Validation;

use PpPhp\Core\Platform\Event\Consumer\Batch\QueueConsumerBatchOptions;
use PpPhp\Core\Platform\Event\Consumer\QueueConsumerManager;
use PpPhp\Core\Platform\Event\Worker\Pool\WorkerPoolManager;

final class QueueConsumerCrossProcessHydrationVerifier
{
    public function verify(string $basePath): array
    {
        $pool = WorkerPoolManager::resetInstance($basePath);
        $pool->clear();
        $pool->ensureDefaultPool(3);
        $pool->save();

        $first = QueueConsumerManager::resetInstance($basePath);
        $first->clear();

        for ($i = 1; $i <= 4; $i++) {
            $first->consumer()->queue()->enqueue('consumer.cross.process.' . $i);
        }

        $batch = $first->consumer()->consumeBatchResult(QueueConsumerBatchOptions::limit(4), static function (): void {});
        $first->save();

        /*
         * Simulate a second PHP CLI process. Live consumer state is empty, so
         * consoleState() must hydrate statistics, snapshot and batch counters
         * from storage/cache/events/consumer/consumer-runtime.json.
         */
        $second = QueueConsumerManager::resetInstance($basePath);
        $state = $second->consoleState()->hydratedState();

        $stats = $state['statistics'] ?? [];
        $batchStats = $state['batchStatistics'] ?? [];
        $snapshot = $state['snapshot'] ?? [];
        $validation = $state['validation'] ?? ['ok' => false];

        $checks = [
            'batchExecution' => $batch->acknowledged() === 4,
            'persisted' => ($state['persisted'] ?? false) === true,
            'hydratedStatistics' => ($stats['consumed'] ?? 0) === 4 && ($stats['acknowledged'] ?? 0) === 4,
            'hydratedBatchStatistics' => ($batchStats['batches'] ?? 0) === 1 && ($batchStats['items'] ?? 0) === 4,
            'hydratedSnapshot' => isset($snapshot['statistics'], $snapshot['queue'], $snapshot['pool']),
            'validation' => ($validation['ok'] ?? false) === true,
            'singleton' => $second === QueueConsumerManager::instance($basePath),
        ];

        $issues = [];
        foreach ($checks as $check => $ok) {
            if (!$ok) {
                $issues[] = ['check' => $check, 'message' => 'Queue consumer cross-process hydration failed: ' . $check];
            }
        }

        return [
            'ok' => !in_array(false, $checks, true),
            'checks' => $checks,
            'issues' => $issues,
            'summary' => [
                'consumed' => $stats['consumed'] ?? 0,
                'acknowledged' => $stats['acknowledged'] ?? 0,
                'batches' => $batchStats['batches'] ?? 0,
                'items' => $batchStats['items'] ?? 0,
                'score' => in_array(false, $checks, true) ? 80 : 100,
            ],
        ];
    }
}
