<?php
/**
 * WP-CLI commands.
 *
 * @package CertaCart_EU_Product_Readiness
 */

namespace CertaCart\EU_Product_Readiness;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

final class Cli_Command {
	public static function register(): void {
		\WP_CLI::add_command( 'certacart scan', array( __CLASS__, 'scan' ) );
		\WP_CLI::add_command( 'certacart status', array( __CLASS__, 'status' ) );
	}

	/**
	 * Run a complete product-readiness scan.
	 *
	 * ## OPTIONS
	 *
	 * [--category=<id>]
	 * : Restrict the scan to a product category term ID.
	 */
	public static function scan( array $args, array $assoc_args ): void {
		$scope = array();
		if ( ! empty( $assoc_args['category'] ) ) {
			$scope['category_id'] = absint( $assoc_args['category'] );
		}
		$scanner = new Scanner();
		$status  = $scanner->start( get_current_user_id(), $scope );
		\WP_CLI::log( sprintf( 'Started scan #%d for %d products.', $status['id'], $status['total_products'] ) );
		do {
			$status = $scanner->process( $status['id'] );
			if ( ! empty( $status['busy'] ) ) {
				usleep( 250000 );
			}
			\WP_CLI::log( sprintf( 'Progress: %s%% (%d/%d)', $status['progress'], $status['processed_products'], $status['total_products'] ) );
		} while ( 'running' === $status['status'] || 'queued' === $status['status'] );

		if ( 'completed' !== $status['status'] ) {
			\WP_CLI::error( $status['error_message'] ?: 'Scan did not complete.' );
		}
		$score = ! empty( $status['score_available'] ) ? sprintf( '%.1f', $status['overall_score'] ) : 'N/A';
		\WP_CLI::success( sprintf( 'Score %s; in scope %d; critical %d; warnings %d.', $score, (int) ( $status['in_scope_products'] ?? 0 ), $status['critical_count'], $status['warning_count'] ) );
	}

	/**
	 * Show the latest scan summary.
	 */
	public static function status(): void {
		$latest = ( new Scan_Repository() )->latest();
		if ( ! $latest ) {
			\WP_CLI::warning( 'No scans found.' );
			return;
		}
		$status = ( new Scanner() )->status( (int) $latest['id'] );
		\WP_CLI::line( wp_json_encode( $status, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES ) );
	}
}
