<?php

namespace WPSN\Cli;

use WPSN\Core\Container;
use WPSN\Modules\Diagnostics\PlatformOpsProbeService;
use WPSN\Modules\Diagnostics\PlatformOpsReportRepository;

defined('ABSPATH') || exit;

/**
 * External platform probe (licensing / billing / SaaS / AI proxy readiness).
 */
final class PlatformCommand
{
    private Container $container;

    public function __construct(Container $container)
    {
        $this->container = $container;
    }

    /**
     * Run the external platform probe.
     *
     * ## OPTIONS
     *
     * [--json]
     * : Output full JSON payload.
     *
     * [--no-save]
     * : Do not store the probe run in wp_options history.
     *
     * ## EXAMPLES
     *
     *     wp wpsn platform
     *     wp wpsn platform --json
     *     wp wpsn platform --no-save
     */
    public function __invoke(array $args, array $assocArgs): void
    {
        $asJson = !empty($assocArgs['json']);
        $save = empty($assocArgs['no-save']);
        $repo = new PlatformOpsReportRepository();
        $previous = $save ? $repo->getLast() : [];

        $report = (new PlatformOpsProbeService($this->container))->run([
            'trigger' => 'wp_cli',
            'source' => 'wp_cli',
        ]);

        if ($save) {
            $repo->save($report);
            do_action('wpsn/platform_ops/run_completed', $report, [
                'trigger' => 'wp_cli',
                'source' => 'wp_cli',
                'previous' => $previous,
            ]);
        }

        $severity = isset($report['severity']) ? (string) $report['severity'] : 'info';

        if ($asJson) {
            \WP_CLI::log((string) wp_json_encode($report, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
        } else {
            $counts = isset($report['counts']) && is_array($report['counts']) ? $report['counts'] : [];
            \WP_CLI::log('WP SEO Next platform probe');
            \WP_CLI::log('Plugin version: ' . (string) ($report['plugin_version'] ?? ''));
            \WP_CLI::log('Severity: ' . $severity);
            \WP_CLI::log(sprintf(
                'Counts: ok=%d warn=%d critical=%d skipped=%d',
                (int) ($counts['ok'] ?? 0),
                (int) ($counts['warn'] ?? 0),
                (int) ($counts['critical'] ?? 0),
                (int) ($counts['skipped'] ?? 0)
            ));

            $checks = isset($report['checks']) && is_array($report['checks']) ? $report['checks'] : [];
            foreach ($checks as $key => $check) {
                if (!is_array($check)) {
                    continue;
                }
                $sev = isset($check['severity']) ? (string) $check['severity'] : 'info';
                $summary = isset($check['summary']) ? (string) $check['summary'] : '';
                $http = isset($check['http_status']) && (int) $check['http_status'] > 0 ? ' HTTP ' . (int) $check['http_status'] : '';
                $prefix = $sev === 'ok' ? '[OK]' : ($sev === 'skipped' ? '[--]' : '[!!]');
                \WP_CLI::log(sprintf('%s %-24s %-9s %s%s', $prefix, (string) $key, $sev, $summary, $http));
            }
        }

        if ($severity === 'critical') {
            \WP_CLI::error('Platform probe found critical backend failures. Open Tools → Platform Ops and inspect the failing checks.');
        }
        if ($severity === 'warn') {
            \WP_CLI::warning('Platform probe finished with warnings.');
            return;
        }
        \WP_CLI::success('Platform probe OK.');
    }
}
