<?php

declare(strict_types=1);

namespace ShieldX\WPCLI;

defined('ABSPATH') || exit;

use ShieldX\Maintenance\LogRotator;

final class LogCommand
{
    /**
     * Inspect or run SHIELD-X log rotation.
     *
     * @synopsis [<status|rotate>] [--yes] [--format=<format>]
     *
     * @param array<int,string>   $args
     * @param array<string,mixed> $assocArgs
     */
    public function __invoke(array $args, array $assocArgs): void
    {
        AdminGate::requireManageOptions();

        $subcommand = isset($args[0]) ? (string) $args[0] : 'status';
        $json = CommandOutput::isJson($assocArgs);

        switch ($subcommand) {
            case 'status':
                $this->status($json);
                return;

            case 'rotate':
                $this->rotate($assocArgs, $json);
                return;

            default:
                \WP_CLI::error('Unknown log command. Use status or rotate.');
        }
    }

    private function status(bool $json): void
    {
        $status = LogRotator::fromWordPress()->status();
        $files = isset($status['files']) && is_array($status['files']) ? $status['files'] : [];

        if ($json) {
            CommandOutput::writeJson([
                'command' => 'log',
                'subcommand' => 'status',
                'status' => $status,
            ]);
            return;
        }

        \WP_CLI::line('Rotation: ' . (!empty($status['enabled']) ? 'enabled' : 'disabled'));
        \WP_CLI::line('Retention days: ' . (string) ($status['retention_days'] ?? 0));
        \WP_CLI::line('File logs: ' . (string) ($files['count'] ?? 0));
        \WP_CLI::line('File bytes: ' . (string) ($files['total_bytes'] ?? 0));
        \WP_CLI::success('SHIELD-X log rotation status completed.');
    }

    /**
     * @param array<string,mixed> $assocArgs
     */
    private function rotate(array $assocArgs, bool $json): void
    {
        \WP_CLI::confirm('Rotate/delete selected SHIELD-X logs now?', $assocArgs);
        $result = LogRotator::fromWordPress()->rotate(true);

        if ($json) {
            CommandOutput::writeJson([
                'command' => 'log',
                'subcommand' => 'rotate',
                'result' => $result,
            ]);
            return;
        }

        \WP_CLI::line('Status: ' . (string) ($result['status'] ?? 'unknown'));
        \WP_CLI::line('Deleted files: ' . (string) ($result['deleted_files'] ?? 0));
        \WP_CLI::line('Deleted bytes: ' . (string) ($result['deleted_bytes'] ?? 0));
        \WP_CLI::line('Trimmed files: ' . (string) ($result['trimmed_files'] ?? 0));
        \WP_CLI::line('Trimmed bytes: ' . (string) ($result['trimmed_bytes'] ?? 0));
        \WP_CLI::line('Deleted DB rows: ' . (string) ($result['deleted_rows'] ?? 0));
        \WP_CLI::success((string) ($result['message'] ?? 'SHIELD-X log rotation completed.'));
    }
}
