<?php
declare(strict_types=1);

namespace Ekesto\CacheWarmup\Integrations;

use Ekesto\CacheWarmup\Debug;

/**
 * Canonical ECW adapter gate delegated to ECI authority.
 */
final class InvalidatorAdapterGate
{
    /**
     * Resolve whether an operational adapter is available.
     *
     * Primary path: ECI AdapterManager::hasOperationalAdapter($context)
     * Fallback path: apply_filters('ekesto_ci_has_operational_adapter', false, $context)
     *
     * @param array<string,mixed> $context
     * @return bool
     */
    public static function hasOperationalAdapter(array $context = []): bool
    {
        $context = array_merge([
            'caller' => '',
            'reason' => '',
            'adapter' => '',
            'cache_enabled' => null,
            'detection_supported' => false,
        ], $context);

        $eciAdapterManager = '\\Ekesto\\CacheInvalidator\\Integrations\\Caching\\AdapterManager';

        if (class_exists($eciAdapterManager) && method_exists($eciAdapterManager, 'hasOperationalAdapter')) {
            try {
                $result = (bool) $eciAdapterManager::hasOperationalAdapter($context);
                Debug::verbose('operational_adapter_gate', [
                    'path' => 'eci_authority',
                    'result' => $result,
                    'caller' => (string) ($context['caller'] ?? ''),
                    'reason' => (string) ($context['reason'] ?? ''),
                ]);
                return $result;
            } catch (\Throwable $throwable) {
                Debug::verbose('operational_adapter_gate exception', [
                    'path' => 'eci_authority',
                    'error' => $throwable->getMessage(),
                    'caller' => (string) ($context['caller'] ?? ''),
                    'reason' => (string) ($context['reason'] ?? ''),
                ]);
                return false;
            }
        }

        $fallback = (bool) apply_filters('ekesto_ci_has_operational_adapter', false, $context);

        Debug::verbose('operational_adapter_gate', [
            'path' => 'filter_override',
            'result' => $fallback,
            'caller' => (string) ($context['caller'] ?? ''),
            'reason' => (string) ($context['reason'] ?? ''),
        ]);

        return $fallback;
    }
}
