<?php
/** WP-CLI diagnostics for durable final publication jobs. */

defined( 'ABSPATH' ) || exit;

class Costudio_Publication_Jobs_CLI {
	public static function register(): void {
		if ( ! defined( 'WP_CLI' ) || ! WP_CLI ) {
			return;
		}
		WP_CLI::add_command( 'costudio publication jobs status', array( __CLASS__, 'status' ) );
		WP_CLI::add_command( 'costudio publication jobs list', array( __CLASS__, 'list_jobs' ) );
		WP_CLI::add_command( 'costudio publication jobs retry', array( __CLASS__, 'retry' ) );
	}

	public static function status(): void {
		WP_CLI::log( wp_json_encode( array(
			'enabled' => Costudio_Publication_Jobs::enabled(),
			'mode' => Costudio_Publication_Jobs::enabled() ? 'automatic' : 'legacy',
			'queue_depth' => Costudio_Publication_Jobs::queue_depth(),
			'configuration_required' => false,
			'studio_version' => COSTUDIO_VERSION,
		), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES ) );
	}

	public static function list_jobs( array $args, array $assoc ): void {
		$limit = max( 1, min( 200, (int) ( $assoc['limit'] ?? 20 ) ) );
		WP_CLI\Utils\format_items( 'table', Costudio_Publication_Jobs::list_rows( $limit ), array(
			'job_id', 'job_status', 'stage', 'production_id', 'driver', 'claim_count', 'worker_id', 'heartbeat_at', 'updated_at', 'finished_at',
		) );
	}

	/** ## OPTIONS <production_id> */
	public static function retry( array $args ): void {
		$id = absint( $args[0] ?? 0 );
		$row = Costudio_Publication_Jobs::ensure_queued( $id, 'wp_cli_retry' );
		if ( ! $row ) {
			WP_CLI::error( 'Could not queue this publication.' );
		}
		Costudio_Publication_Jobs::ensure_progress( $id, 'wp_cli_retry' );
		WP_CLI::success( 'Publication queued.' );
	}
}
