<?php
namespace QuantumCache\Cli;

\defined( 'ABSPATH' ) || exit;

use QuantumCache\Support\Metrics;
use QuantumCache\Support\Stats;
use QuantumCache\Support\StoreFactory;

/**
 * Show QuantumCache backend status, storage stats, and lifetime event counters.
 *
 * ## EXAMPLES
 *
 *     wp quantumcache status
 *
 * @when after_wp_load
 */
final class StatusCommand {

	/**
	 * @param string[]             $args       Positional arguments (unused).
	 * @param array<string,string> $assoc_args Named arguments (unused).
	 */
	public function __invoke( array $args, array $assoc_args ): void {
		$store_name = StoreFactory::storeName();
		$prefix     = StoreFactory::sitePrefix();

		\WP_CLI::line( 'Backend  : ' . $store_name );
		\WP_CLI::line( 'Prefix   : ' . $prefix );
		\WP_CLI::line( '' );

		// Storage stats.
		$stats = Stats::collect();
		\WP_CLI::line( '--- Storage ---' );
		\WP_CLI\Utils\format_items(
			'table',
			array(
				array( 'metric' => 'Entries',     'value' => (string) $stats['entries'] ),
				array( 'metric' => 'Tags',         'value' => (string) $stats['tags'] ),
				array( 'metric' => 'Bytes',        'value' => null !== $stats['bytes'] ? number_format( (int) $stats['bytes'] ) : 'n/a' ),
				array( 'metric' => 'Oldest entry', 'value' => $stats['oldest'] ?? 'n/a' ),
				array( 'metric' => 'Newest entry', 'value' => $stats['newest'] ?? 'n/a' ),
				array( 'metric' => 'Approximate',  'value' => $stats['approximate'] ? 'yes' : 'no' ),
			),
			array( 'metric', 'value' )
		);

		if ( $stats['note'] ) {
			\WP_CLI::warning( $stats['note'] );
		}

		// Lifetime event counters.
		$totals = Metrics::totals();
		\WP_CLI::line( '' );
		\WP_CLI::line( '--- Lifetime event counters ---' );
		\WP_CLI\Utils\format_items(
			'table',
			array(
				array( 'counter' => 'Query hits',    'total' => number_format( $totals['query_hits'] ) ),
				array( 'counter' => 'Query misses',  'total' => number_format( $totals['query_misses'] ) ),
				array( 'counter' => 'Query stores',  'total' => number_format( $totals['query_stores'] ) ),
				array( 'counter' => 'Frag hits',     'total' => number_format( $totals['frag_hits'] ) ),
				array( 'counter' => 'Frag misses',   'total' => number_format( $totals['frag_misses'] ) ),
				array( 'counter' => 'Frag stores',   'total' => number_format( $totals['frag_stores'] ) ),
				array( 'counter' => 'Purge calls',   'total' => number_format( $totals['purge_calls'] ) ),
				array( 'counter' => 'Tags purged',   'total' => number_format( $totals['purge_tags'] ) ),
			),
			array( 'counter', 'total' )
		);
	}
}
