<?php

declare(strict_types=1);

namespace Numinix\SeekmodoWordPress\Admin;

use Numinix\SeekmodoWordPress\Config\Options;
use Numinix\SeekmodoWordPress\Events\EventsQueue;
use Numinix\SeekmodoWordPress\Gateway\CircuitBreaker;
use Numinix\SeekmodoWordPress\LocalIndex\Indexer as LocalIndexer;
use Numinix\SeekmodoWordPress\LocalIndex\VerticalConfig;
use Numinix\SeekmodoWordPress\Mode\AutoPromoter;
use Numinix\SeekmodoWordPress\Mode\ModeFsm;

/**
 * Dashboard widget that prints a one-screen health summary:
 *   - Mode + effective mode (substate, if active).
 *   - Circuit breaker state.
 *   - 5-min rolling p95 / 5xx / fallback gauges.
 *   - Indexer cursor (last tick / docs / fails).
 *   - Events queue depth.
 *
 * This is the "did the connector even fire?" eyeball check operators
 * land on after deploying a new tenant.
 */
final class HealthWidget
{
    public static function register(): void
    {
        if (!function_exists('add_action')) {
            return;
        }
        add_action('wp_dashboard_setup', [self::class, 'addWidget']);
    }

    public static function addWidget(): void
    {
        if (!function_exists('wp_add_dashboard_widget')) {
            return;
        }
        if (!function_exists('current_user_can') || !current_user_can('manage_options')) {
            return;
        }
        wp_add_dashboard_widget(
            'seekmodo_health_widget',
            esc_html__('Seekmodo health', 'seekmodo'),
            [self::class, 'render']
        );
    }

    public static function render(): void
    {
        if (!function_exists('current_user_can') || !current_user_can('manage_options')) {
            return;
        }
        $paired   = Options::isPaired();
        $mode     = ModeFsm::current();
        $effmode  = AutoPromoter::effectiveMode();
        $breaker  = CircuitBreaker::state();
        $metrics  = AutoPromoter::metrics();
        $cursor   = get_option(Options::OPT_INDEXER_CURSOR);
        $queue_n  = EventsQueue::count();
        $last_pull = (int) get_option(Options::OPT_LAST_SNAPSHOT_AT, 0);
        $local     = LocalIndexer::status();
        $local_on  = VerticalConfig::isEnabled() && VerticalConfig::mode() !== VerticalConfig::MODE_OFF;

        echo '<style>.seekmodo-h-grid{display:grid;grid-template-columns:max-content auto;gap:4px 16px;}</style>';
        echo '<div class="seekmodo-h-grid">';
        self::row(__('Paired', 'seekmodo'),  $paired ? '✓ yes' : '— no');
        self::row(__('Mode (operator)', 'seekmodo'),   $mode);
        self::row(__('Mode (effective)', 'seekmodo'),  $effmode);
        self::row(__('Breaker', 'seekmodo'),           $breaker);
        if ($local_on) {
            $local_label = sprintf(
                '%d docs / %d rows (%s)',
                (int) $local['docs'],
                (int) $local['rows'],
                VerticalConfig::mode()
            );
            if ((int) $local['docs'] === 0) {
                $local_label .= ' — ' . __('building…', 'seekmodo');
            }
            self::row(__('Local index', 'seekmodo'), $local_label);
        }
        self::row(__('p95 latency', 'seekmodo'),       (int) $metrics['p95_ms'] . ' ms');
        self::row(__('p50 latency', 'seekmodo'),       (int) $metrics['p50_ms'] . ' ms');
        self::row(__('5xx rate', 'seekmodo'),          number_format(((float) $metrics['r5xx']) * 100, 1) . '%');
        self::row(__('Fallback rate', 'seekmodo'),     number_format(((float) $metrics['rfb']) * 100, 1) . '%');
        self::row(__('Sample window', 'seekmodo'),     (int) $metrics['samples'] . ' obs / 5 min');
        if (is_array($cursor)) {
            self::row(__('Last index tick', 'seekmodo'),
                isset($cursor['last_tick_at']) ? human_time_diff((int) $cursor['last_tick_at']) . ' ago' : '—');
            self::row(__('Last index docs', 'seekmodo'),
                sprintf('%d indexed / %d failed', (int) ($cursor['last_indexed'] ?? 0), (int) ($cursor['last_failed'] ?? 0)));
        }
        self::row(__('Events queue', 'seekmodo'),      (string) $queue_n);
        self::row(__('Snapshot pull', 'seekmodo'),
            $last_pull > 0 ? human_time_diff($last_pull) . ' ago' : '—');
        echo '</div>';

        echo '<p style="margin-top:1em;">';
        printf(
            '<a href="%s">%s</a> &middot; <a href="https://admin.seekmodo.com" target="_blank" rel="noopener">admin.seekmodo.com →</a>',
            esc_url(admin_url('options-general.php?page=' . SettingsPage::SLUG)),
            esc_html__('Open settings', 'seekmodo')
        );
        echo '</p>';
    }

    private static function row(string $label, string $value): void
    {
        printf(
            '<div><strong>%s</strong></div><div><code>%s</code></div>',
            esc_html($label),
            esc_html($value)
        );
    }
}
