<?php

// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedNamespaceFound -- APD is the established namespace shared with the Pro add-on and retained for backward compatibility.
namespace APD\Operations;

use APD\Support\ProductionReadiness;

defined('ABSPATH') || exit;

class ProductionCliCommand
{
    /**
     * Validate WordPress, WooCommerce, licensing, cron, mail, and release metadata.
     *
     * ## OPTIONS
     *
     * [--format=<format>]
     * : table or json. Default: table.
     *
     * [--strict]
     * : Treat warnings as failures.
     */
    public function __invoke(array $args, array $assocArgs) : void
    {
        unset($args);
        $result = (new ProductionReadiness())->evaluate();
        $format = sanitize_key((string) ($assocArgs['format'] ?? 'table'));

        if ($format === 'json') {
            \WP_CLI::line((string) wp_json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
        } else {
            \WP_CLI\Utils\format_items(
                'table',
                array_map(static fn(array $check) : array => [
                    'status' => strtoupper((string) $check['status']),
                    'check' => (string) $check['label'],
                    'detail' => (string) $check['detail'],
                ], $result['checks']),
                ['status', 'check', 'detail']
            );
            \WP_CLI::line(sprintf(
                'Passed: %d | Warnings: %d | Failed: %d',
                $result['summary']['passed'],
                $result['summary']['warnings'],
                $result['summary']['failed']
            ));
        }

        if (! $result['ready']) {
            \WP_CLI::error(__('Production preflight failed.', 'asuka-product-designer'));
        }
        if (! empty($assocArgs['strict']) && $result['summary']['warnings'] > 0) {
            \WP_CLI::error(__('Production preflight still contains warnings.', 'asuka-product-designer'));
        }

        \WP_CLI::success(__('Core production checks passed.', 'asuka-product-designer'));
    }
}
