<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Event\Verification;

use PpPhp\Core\Platform\Event\Compiler\ListenerRegistryCompiler;
use PpPhp\Core\Platform\Event\Contracts\EventInterface;
use PpPhp\Core\Platform\Event\Registry\EventListenerRegistry;
use PpPhp\Core\Platform\Event\Runtime\EventRuntimeRegistry;
use PpPhp\Core\Platform\Event\Subscriber\EventSubscriberInterface;

final class ListenerRegistryVerifier
{
    public function verify(string $basePath): array
    {
        $issues = [];
        $runtime = new EventRuntimeRegistry();

        $runtime->registry()->register('registry.verify', static function (EventInterface $event): void {}, 10, ['verify']);

        $subscriber = new class implements EventSubscriberInterface {
            public static function subscribedEvents(): array
            {
                return ['registry.subscriber' => ['onEvent', 50]];
            }

            public function onEvent(EventInterface $event): void {}
        };
        $runtime->registerSubscriber($subscriber);

        $manifestCount = $runtime->loadManifest([
            'events' => [
                'listeners' => [
                    [
                        'event' => 'registry.manifest',
                        'listener' => self::class . '::staticListener',
                        'priority' => 5,
                    ],
                ],
            ],
        ], $basePath);

        $compiled = (new ListenerRegistryCompiler())->compile($runtime->registry(), $basePath);

        $checks = [
            'registry' => $runtime->registry()->count() >= 2,
            'subscriber' => in_array('registry.subscriber', $runtime->registry()->events(), true),
            'manifest' => $manifestCount >= 1,
            'compiler' => ($compiled['listenerCount'] ?? 0) === $runtime->registry()->count(),
            'dispatchTable' => isset($compiled['dispatchTable']['registry.verify']),
        ];

        foreach ($checks as $check => $ok) {
            if (!$ok) {
                $issues[] = ['check' => $check, 'message' => 'Listener registry verification failed: ' . $check];
            }
        }

        return [
            'ok' => !in_array(false, $checks, true),
            'checks' => $checks,
            'issues' => $issues,
            'summary' => $runtime->summary() + [
                'compiledListeners' => $compiled['listenerCount'] ?? 0,
                'compiledEvents' => count($compiled['events'] ?? []),
                'score' => in_array(false, $checks, true) ? 80 : 100,
            ],
        ];
    }

    public static function staticListener(EventInterface $event): void {}
}
