<?php

namespace MintyPHP\Console\Commands\Module;

final class RuntimeSyncCommand extends AbstractModuleCommand
{
    public function name(): string
    {
        return 'module:sync';
    }

    public function description(): string
    {
        return 'Run full module runtime sync (migrate, permissions, build, assets)';
    }

    public function usage(): string
    {
        return <<<'USAGE'
        Usage: php bin/console module:sync [--format=json]

        Options:
          --format=json    Output stable JSON for automation
        USAGE;
    }

    public function execute(array $args, array $options): int
    {
        $format = strtolower((string) ($options['format'] ?? 'human'));
        if (!in_array($format, ['human', 'json'], true)) {
            fwrite(STDERR, "Invalid format '{$format}'. Supported: human, json\n");
            return 1;
        }

        $result = $this->moduleRunner()->runtimeSync();

        if ($format === 'json') {
            echo json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) . PHP_EOL;
            return (int) $result['exit_code'];
        }

        foreach ($result['steps'] as $stepName => $step) {
            echo sprintf(
                "module-runtime-sync: step=%s status=%s exit_code=%d vendor_warnings_ignored=%d\n",
                $stepName,
                $step['status'],
                $step['exit_code'],
                $step['vendor_warnings_ignored']
            );
        }
        echo $result['message'] . PHP_EOL;

        return (int) $result['exit_code'];
    }
}
