#!/usr/bin/env php
<?php
Phar::mapPhar('wm.phar');
require 'phar://wm.phar/bin/wm';
__HALT_COMPILER(); ?>
  	          wm.phar       bin/wm        «Πθν         src/autoload.php        φ€         src/App.phpΔ      Δ  °i1.€         src/Runtime.phpό      ό  ΊH€         src/Registry.phpϊ      ϊ  ό€         src/Project.php6      6  ή€         src/Systemd.phpΧ      Χ  υ€         src/Process.php*	      *	  άη΄ο€      
   src/UI.php!      !  © €      #!/usr/bin/env php
<?php

declare(strict_types=1);

$autoload = __DIR__ . '/../src/autoload.php';
if (class_exists('Phar') && Phar::running(false) !== '') {
    $autoload = 'phar://' . Phar::running(false) . '/src/autoload.php';
}
require $autoload;
exit((new WM\App())->run($argv));
<?php

declare(strict_types=1);

spl_autoload_register(static function (string $class): void {
    if (str_starts_with($class, 'WM\\')) {
        $file = __DIR__ . '/' . substr($class, 3) . '.php';
        if (is_file($file)) {
            require $file;
        }
    }
});
<?php

declare(strict_types=1);

namespace WM;

use RuntimeException;
use Throwable;

final class App
{
    private Registry $registry;
    private Systemd $systemd;
    private UI $ui;
    private bool $nonInteractive = false;

    public function __construct()
    {
        $this->registry = new Registry((string) (getenv('WM_CONFIG_DIR') ?: '/etc/wm/projects.d'));
        $this->systemd = new Systemd((string) (getenv('WM_UNIT_DIR') ?: '/etc/systemd/system'), (string) (getenv('WM_SYSTEMCTL') ?: '/usr/bin/systemctl'));
        $this->ui = new UI(false, false);
    }

    /** @param list<string> $argv */
    public function run(array $argv): int
    {
        $args = array_slice($argv, 1);
        $json = false;
        try {
            $json = $this->extractFlag($args, '--json');
            $this->ui = new UI(false, $json); // Error output is valid even if option parsing fails.
            $plain = $this->extractFlag($args, '--no-ansi');
            $color = $this->extractColor($args);
            $this->nonInteractive = $this->extractFlag($args, '--no-interaction');
            $ansi = !$json && !$plain && ($color === 'always' || ($color === 'auto'
                && getenv('NO_COLOR') === false && function_exists('stream_isatty') && stream_isatty(STDOUT)));
            $this->ui = new UI($ansi, $json);
            $command = array_shift($args);
            if ($command === null) {
                if (!$this->nonInteractive && $this->ui->interactive()) {
                    return $this->menu();
                }
                return $this->help();
            }
            if (in_array($command, ['--help', '-h', 'help'], true)) {
                return $this->help();
            }
            if (in_array($command, ['--version', '-V', 'version'], true)) {
                $this->ui->output(['version' => '0.1.2']);
                if (!$json) {
                    echo "WM 0.1.2\n";
                }
                return 0;
            }
            [$pos, $opts] = $this->parse($args);
            return match ($command) {
                'add' => $this->add($pos, $opts),
                'ls', 'list' => $this->listing($pos, $opts),
                'status', 'info' => $this->status($pos, $opts, $command === 'info'),
                'start', 'stop', 'restart', 'reload', 'enable', 'disable' => $this->manage($command, $pos, $opts),
                'remove', 'rm' => $this->remove($pos, $opts),
                'sync' => $this->sync($pos, $opts),
                'doctor' => $this->doctor($pos, $opts),
                'logs' => $this->logs($pos, $opts),
                'import' => $this->import($pos, $opts),
                default => throw new RuntimeException("Unknown command: {$command}. Run 'wm help'."),
            };
        } catch (Throwable $e) {
            if ($json) {
                $this->ui->output(['ok' => false, 'error' => $e->getMessage()]);
            } else {
                fwrite(STDERR, $this->ui->color('β ', '1;31') . $e->getMessage() . "\n");
            }
            return 1;
        }
    }

    /** @param list<string> $args */
    private function extractFlag(array &$args, string $flag): bool
    {
        $found = false;
        $args = array_values(array_filter($args, static function (string $arg) use ($flag, &$found): bool {
            if ($arg === $flag) {
                $found = true;
                return false;
            }
            return true;
        }));
        return $found;
    }

    /** @param list<string> $args */
    private function extractColor(array &$args): string
    {
        $color = 'auto';
        $filtered = [];
        for ($i = 0; $i < count($args); ++$i) {
            $arg = $args[$i];
            if ($arg !== '--color' && !str_starts_with($arg, '--color=')) {
                $filtered[] = $arg;
                continue;
            }
            $value = $arg === '--color' ? ($args[++$i] ?? '') : substr($arg, strlen('--color='));
            if (!in_array($value, ['auto', 'always', 'never'], true)) {
                throw new RuntimeException('--color must be auto, always, or never.');
            }
            $color = $value;
        }
        $args = $filtered;
        return $color;
    }

    /** @param list<string> $args
     *  @return array{0:list<string>,1:array<string,string|bool>}
     */
    private function parse(array $args): array
    {
        $positionals = [];
        $options = [];
        $flags = ['all', 'now', 'enable', 'yes', 'dry-run', 'recursive', 'force', 'follow'];
        $values = ['type', 'php', 'user', 'entry', 'mode', 'pid-file', 'lines', 'source'];
        for ($i = 0; $i < count($args); ++$i) {
            $arg = $args[$i];
            if ($arg === '-f') {
                $options['follow'] = true;
                continue;
            }
            if ($arg === '--') {
                array_push($positionals, ...array_slice($args, $i + 1));
                break;
            }
            if (!str_starts_with($arg, '--')) {
                $positionals[] = $arg;
                continue;
            }
            [$key, $inline] = array_pad(explode('=', substr($arg, 2), 2), 2, null);
            if (in_array($key, $flags, true)) {
                if ($inline !== null) {
                    throw new RuntimeException("Flag --{$key} does not accept a value.");
                }
                $options[$key] = true;
            } elseif (in_array($key, $values, true)) {
                $value = $inline ?? ($args[++$i] ?? null);
                if ($value === null || $value === '' || str_starts_with($value, '--')) {
                    throw new RuntimeException("Missing value for --{$key}");
                }
                $options[$key] = $value;
            } else {
                throw new RuntimeException("Unknown option: --{$key}");
            }
        }
        return [$positionals, $options];
    }

    /** @param array<string,string|bool> $opts
     *  @param list<string> $allowed
     */
    private function checkOptions(array $opts, array $allowed): void
    {
        foreach ($opts as $key => $_) {
            if (!in_array($key, $allowed, true)) {
                throw new RuntimeException("Unsupported option for this command: --{$key}");
            }
        }
    }

    /** @param list<string> $args */
    private function exactly(array $args, int $min, int $max): void
    {
        if (count($args) < $min || count($args) > $max) {
            throw new RuntimeException("Expected {$min}" . ($min === $max ? '' : "β{$max}") . ' argument(s). See wm help.');
        }
    }

    private function help(): int
    {
        $help = <<<'HELP'
WM β Webman / Workerman process manager                         v0.1.2

USAGE
  wm [command] [arguments] [options]

PROJECTS
  add <name> <path>          Register a project; does not start by default
  import <dir> --recursive  Discover and register projects
  ls                         List registered projects and live states
  info <name>                Detailed project information
  status [name]              Live status of one or all projects
  remove <name>              Unregister (does not delete project files)
  sync [name]                Regenerate systemd units from registry
  doctor [name]              Validate project and server configuration

LIFECYCLE
  start|stop|restart|reload <name>    Operate one project
  start|stop|restart|reload --all     Operate all projects
  enable|disable <name> [--now]      Manage auto-start (also start/stop with --now)
  enable|disable --all               Manage all projects
  logs <name> [-f]                    Follow or view logs

ADD OPTIONS
  --type webman|workerman    Auto-detected when possible
  --mode daemon|foreground  Defaults: webman=daemon, workerman=foreground
  --php /path/php           Default: php in PATH
  --user USER               Service user (defaults to current user; root allowed)
  --entry start.php         Entry file (relative to project)
  --pid-file /absolute/path Required for Workerman daemon mode
  --enable                  Enable start on boot
  --now                     Start service after registering
  --dry-run                 Show generated unit without writing

OTHER OPTIONS
  --yes                     Skip confirmation for remove/import
  --recursive               Recursively scan directories for import
  --source auto|journal|stdout|workerman|app   Logs source
  --lines 100               Number of log lines
  --json                    Structured output; disables ANSI
  --no-ansi                 Disable terminal colors
  --color auto|always|never  Color policy (auto respects NO_COLOR and TTY)
  --no-interaction          Never prompt for input

EXAMPLES
  sudo wm add auth /srv/auth --enable --now
  sudo wm add chat /srv/chat --type workerman --user www-data
  wm ls
  wm restart --all
  wm logs auth -f

Run 'wm' without arguments in a terminal for an interactive menu.
HELP;
        $this->ui->output(['help' => $help]);
        if (!$this->ui->json) {
            echo $help . "\n";
        }
        return 0;
    }

    /** @param list<string> $pos
     *  @param array<string,string|bool> $opts
     */
    private function add(array $pos, array $opts): int
    {
        $this->checkOptions($opts, ['type', 'php', 'user', 'entry', 'mode', 'pid-file', 'enable', 'now', 'dry-run']);
        $this->exactly($pos, 0, 2);
        $name = $pos[0] ?? null;
        $path = $pos[1] ?? null;
        if (($name === null || $path === null) && !$this->nonInteractive && $this->ui->interactive()) {
            $this->ui->title('Register a new project');
            $path ??= $this->ui->ask('Project directory');
            $name ??= $this->ui->ask('Project name', $this->suggestName($path));
        }
        if (!$name || !$path) {
            throw new RuntimeException('Usage: wm add <name> <path> [--type ...] [--enable] [--now]');
        }
        $settings = ['name' => $name, 'path' => $path];
        foreach (['type' => 'type', 'php' => 'php', 'user' => 'user', 'entry' => 'entry', 'mode' => 'mode', 'pid-file' => 'pid_file'] as $option => $key) {
            if (isset($opts[$option])) {
                $settings[$key] = $opts[$option];
            }
        }
        $project = Project::create($settings);
        $unit = $this->systemd->render($project);
        if (isset($opts['dry-run'])) {
            if ($this->ui->json) {
                $this->ui->output(['project' => $project, 'unit' => $unit, 'dry_run' => true]);
            } else {
                $this->ui->title('Dry-run Β· ' . $project['name']);
                $this->ui->line($unit);
            }
            return 0;
        }
        $this->addProject($project, isset($opts['enable']), isset($opts['now']));
        $this->ui->output(['ok' => true, 'project' => $project, 'enabled' => isset($opts['enable']), 'started' => isset($opts['now'])]);
        $this->ui->ok("Registered {$project['name']} ({$project['type']}, {$project['mode']})");
        $pid = Project::existingPid($project);
        if ($pid !== null && !isset($opts['now'])) {
            $this->ui->warning("An existing process is using PID {$pid}; stop it cleanly before systemd takes over.");
        }
        return 0;
    }

    /** @param array<string,mixed> $project */
    private function addProject(array $project, bool $enable, bool $now): void
    {
        $name = $project['name'];
        if ($now) {
            $this->assertNoUnmanagedProcess($project);
        }
        $this->locked(function () use ($project, $name): void {
            if (is_file($this->registry->file($name))) {
                throw new RuntimeException("Project already registered: {$name}");
            }
            $this->systemd->install($project);
            try {
                $this->registry->put($project);
                $this->systemd->reload();
            } catch (Throwable $e) {
                $this->registry->remove($name);
                $this->systemd->remove($name);
                try {
                    $this->systemd->reload();
                } catch (Throwable) {
                }
                throw $e;
            }
        });
        if ($enable) {
            $this->systemd->must(['enable', $this->systemd->unitName($name)]);
        }
        if ($now) {
            $this->systemd->must(['start', $this->systemd->unitName($name)]);
        }
    }

    /** @param array<string,mixed> $project */
    private function assertNoUnmanagedProcess(array $project): void
    {
        $pid = Project::existingPid($project);
        $state = $this->systemd->show($project['name']);
        if ($pid !== null && ($state['ActiveState'] ?? '') !== 'active') {
            throw new RuntimeException("Existing unmanaged PID {$pid} detected. Project registered, but not started. Stop the existing instance first.");
        }
    }

    /** @param list<string> $pos
     *  @param array<string,string|bool> $opts
     */
    private function listing(array $pos, array $opts): int
    {
        $this->checkOptions($opts, []);
        $this->exactly($pos, 0, 0);
        $data = [];
        foreach ($this->registry->all() as $project) {
            $state = $this->systemd->show($project['name']);
            $data[] = [
                'name' => $project['name'],
                'type' => $project['type'],
                'user' => $project['user'],
                'mode' => $project['mode'],
                'state' => $state['ActiveState'] ?? 'unknown',
                'enabled' => $state['UnitFileState'] ?? 'unknown',
                'pid' => (int) ($state['MainPID'] ?? 0),
                'path' => $project['path'],
            ];
        }
        $this->ui->output(['projects' => $data, 'total' => count($data)]);
        if (!$this->ui->json) {
            $this->ui->title('WM  /  Projects');
            $running = count(array_filter($data, static fn (array $p): bool => $p['state'] === 'active'));
            $enabled = count(array_filter($data, static fn (array $p): bool => in_array($p['enabled'], ['enabled', 'enabled-runtime'], true)));
            $failed = count(array_filter($data, static fn (array $p): bool => $p['state'] === 'failed'));
            $this->ui->projectSummary(count($data), $running, $enabled, $failed);
            // The full path stays in wm info / JSON; avoid an overly wide terminal table.
            $includePath = $this->ui->terminalWidth() >= 135;
            $rows = [];
            $styles = [];
            foreach ($data as $index => $p) {
                $root = $p['user'] === 'root';
                $rows[] = [
                    $p['name'], $p['type'], $root ? 'root !' : $p['user'],
                    $this->ui->stateLabel($p['state']),
                    $this->ui->bootLabel($p['enabled']),
                    (string) ($p['pid'] ?: 'β'),
                ];
                if ($includePath) {
                    $rows[$index][] = $p['path'];
                }
                $styles[$index] = [0 => '1', 3 => $this->ui->stateStyle($p['state']), 4 => $this->ui->bootStyle($p['enabled'])];
                if ($root) {
                    $styles[$index][2] = '1;33'; // Warning only; root is a supported run user.
                }
            }
            $columns = ['NAME', 'TYPE', 'USER', 'STATUS', 'AUTOSTART', 'PID'];
            if ($includePath) {
                $columns[] = 'PATH';
            }
            $this->ui->table($columns, $rows, $styles);
        }
        return 0;
    }

    /** @param list<string> $pos
     *  @param array<string,string|bool> $opts
     */
    private function status(array $pos, array $opts, bool $detail): int
    {
        $this->checkOptions($opts, $detail ? [] : ['all']);
        $this->exactly($pos, $detail ? 1 : 0, isset($opts['all']) ? 0 : 1);
        if ($pos === []) {
            return $this->listing([], []);
        }
        $project = $this->registry->get($pos[0]);
        $state = $this->systemd->show($project['name']);
        $data = ['project' => $project, 'systemd' => $state, 'unit' => $this->systemd->unitPath($project['name'])];
        $this->ui->output($data);
        if (!$this->ui->json) {
            $this->ui->title(($detail ? 'WM  /  Info  /  ' : 'WM  /  Status  /  ') . $project['name']);
            $this->ui->section('Application');
            foreach (['type', 'path', 'entry', 'php', 'user', 'mode', 'pid_file'] as $key) {
                $value = (string) ($project[$key] ?? 'β');
                $this->ui->keyValue($key, $key === 'user' && $value === 'root' ? 'root !' : $value,
                    $key === 'user' && $value === 'root' ? '1;33' : null);
            }
            $this->ui->line();
            $this->ui->section('systemd');
            $this->ui->keyValue('ActiveState', $this->ui->stateLabel($state['ActiveState'] ?? 'unknown'),
                $this->ui->stateStyle($state['ActiveState'] ?? 'unknown'));
            $this->ui->keyValue('UnitFileState', $this->ui->bootLabel($state['UnitFileState'] ?? 'unknown'),
                $this->ui->bootStyle($state['UnitFileState'] ?? 'unknown'));
            foreach (['LoadState', 'SubState', 'MainPID', 'ActiveEnterTimestamp', 'NeedDaemonReload'] as $key) {
                $this->ui->keyValue($key, $state[$key] ?? 'β');
            }
            $this->ui->line();
        }
        return 0;
    }

    /** @param list<string> $pos
     *  @param array<string,string|bool> $opts
     */
    private function manage(string $action, array $pos, array $opts): int
    {
        $this->checkOptions($opts, ['all', 'now']);
        if (isset($opts['now']) && !in_array($action, ['enable', 'disable'], true)) {
            throw new RuntimeException('--now is only supported with enable/disable (or add).');
        }
        $all = isset($opts['all']);
        $this->exactly($pos, $all ? 0 : 1, $all ? 0 : 1);
        $projects = $all ? $this->registry->all() : [$this->registry->get($pos[0])];
        $results = [];
        $failed = false;
        foreach ($projects as $project) {
            $name = $project['name'];
            try {
                if (in_array($action, ['start', 'restart'], true) || ($action === 'enable' && isset($opts['now']))) {
                    $this->assertNoUnmanagedProcess($project);
                }
                $args = [$action];
                if (isset($opts['now'])) {
                    $args[] = '--now';
                }
                $args[] = $this->systemd->unitName($name);
                $this->systemd->must($args);
                $results[$name] = 'ok';
                $this->ui->ok("{$action}: {$name}");
            } catch (Throwable $e) {
                $failed = true;
                $results[$name] = $e->getMessage();
                if (!$this->ui->json) {
                    $this->ui->warning("{$action} {$name}: {$e->getMessage()}");
                }
            }
        }
        $this->ui->output(['ok' => !$failed, 'action' => $action, 'results' => $results]);
        return $failed ? 1 : 0;
    }

    /** @param list<string> $pos
     *  @param array<string,string|bool> $opts
     */
    private function remove(array $pos, array $opts): int
    {
        $this->checkOptions($opts, ['yes']);
        $this->exactly($pos, 1, 1);
        $name = $pos[0];
        $this->registry->get($name);
        if (is_file($this->systemd->unitPath($name)) && !$this->systemd->unitOwned($name)) {
            throw new RuntimeException('Cannot remove an unmanaged service unit.');
        }
        $state = $this->systemd->show($name);
        $active = in_array($state['ActiveState'] ?? '', ['active', 'activating', 'reloading'], true);
        if (!isset($opts['yes'])) {
            if ($this->nonInteractive || !$this->ui->interactive() || !$this->ui->confirm("Unregister {$name}" . ($active ? ' (running service will be stopped)' : '') . '?')) {
                throw new RuntimeException('Confirmation required. Use --yes to unregister.');
            }
        }
        if ($active) {
            $this->systemd->must(['stop', $this->systemd->unitName($name)]);
        }
        if (is_file($this->systemd->unitPath($name))) {
            $this->systemd->must(['disable', $this->systemd->unitName($name)]);
        }
        $this->locked(function () use ($name): void {
            $this->systemd->remove($name);
            $this->systemd->reload();
            $this->registry->remove($name);
        });
        $this->ui->output(['ok' => true, 'removed' => $name, 'source_deleted' => false]);
        $this->ui->ok("Unregistered {$name} (project source untouched)");
        return 0;
    }

    /** @param list<string> $pos
     *  @param array<string,string|bool> $opts
     */
    private function sync(array $pos, array $opts): int
    {
        $this->checkOptions($opts, ['dry-run']);
        $this->exactly($pos, 0, 1);
        $projects = $pos ? [$this->registry->get($pos[0])] : $this->registry->all();
        $changes = [];
        $this->locked(function () use ($projects, &$changes, $opts): void {
            foreach ($projects as $project) {
                $file = $this->systemd->unitPath($project['name']);
                $expected = $this->systemd->render($project);
                $old = is_file($file) ? (string) file_get_contents($file) : null;
                if ($old !== $expected) {
                    if ($old !== null && !$this->systemd->unitOwned($project['name'])) {
                        throw new RuntimeException("Refusing to overwrite unmanaged unit: {$file}");
                    }
                    $changes[] = $project['name'];
                    if (!isset($opts['dry-run'])) {
                        $this->systemd->install($project);
                    }
                }
            }
            if ($changes !== [] && !isset($opts['dry-run'])) {
                $this->systemd->reload();
            }
        });
        $this->ui->output(['ok' => true, 'changed' => $changes, 'dry_run' => isset($opts['dry-run'])]);
        $this->ui->ok(count($changes) . (isset($opts['dry-run']) ? ' unit(s) would change' : ' unit(s) synchronized'));
        return 0;
    }

    /** @param list<string> $pos
     *  @param array<string,string|bool> $opts
     */
    private function doctor(array $pos, array $opts): int
    {
        $this->checkOptions($opts, []);
        $this->exactly($pos, 0, 1);
        $checks = [];
        $checks[] = ['check' => 'OS', 'ok' => PHP_OS_FAMILY === 'Linux', 'detail' => PHP_OS_FAMILY];
        $checks[] = ['check' => 'PHP CLI', 'ok' => PHP_VERSION_ID >= 80200, 'detail' => PHP_VERSION];
        $checks[] = ['check' => 'systemctl executable', 'ok' => is_executable((string) (getenv('WM_SYSTEMCTL') ?: '/usr/bin/systemctl')), 'detail' => (string) (getenv('WM_SYSTEMCTL') ?: '/usr/bin/systemctl')];
        $checks[] = ['check' => 'registry writable', 'ok' => Runtime::canCreateWithin($this->registry->directory), 'detail' => $this->registry->directory];
        $checks[] = ['check' => 'unit dir writable', 'ok' => is_writable($this->systemd->unitDirectory), 'detail' => $this->systemd->unitDirectory];
        $projects = $pos ? [$this->registry->get($pos[0])] : $this->registry->all();
        foreach ($projects as $p) {
            $prefix = $p['name'] . ': ';
            $checks[] = ['check' => $prefix . 'entry', 'ok' => is_file($p['path'] . '/' . $p['entry']), 'detail' => $p['entry']];
            $checks[] = ['check' => $prefix . 'PHP', 'ok' => is_executable($p['php']), 'detail' => $p['php']];
            $checks[] = ['check' => $prefix . 'user', 'ok' => !function_exists('posix_getpwnam') || posix_getpwnam($p['user']) !== false, 'detail' => $p['user']];
            if ($p['mode'] === 'daemon') {
                $checks[] = ['check' => $prefix . 'PID directory', 'ok' => is_dir(dirname($p['pid_file'])) && is_writable(dirname($p['pid_file'])), 'detail' => $p['pid_file']];
            }
            $checks[] = ['check' => $prefix . 'unit', 'ok' => $this->systemd->unitOwned($p['name']), 'detail' => $this->systemd->unitPath($p['name'])];
        }
        $ok = !in_array(false, array_column($checks, 'ok'), true);
        $this->ui->output(['ok' => $ok, 'checks' => $checks]);
        if (!$this->ui->json) {
            $this->ui->title('WM  /  Diagnostics');
            foreach ($checks as $check) {
                $this->ui->line('  ' . $this->ui->color($check['ok'] ? 'β' : 'β', $check['ok'] ? '32' : '31') . ' ' . str_pad($check['check'], 26) . ' ' . $check['detail']);
            }
            $this->ui->line();
        }
        return $ok ? 0 : 1;
    }

    /** @param list<string> $pos
     *  @param array<string,string|bool> $opts
     */
    private function logs(array $pos, array $opts): int
    {
        $this->checkOptions($opts, ['source', 'lines', 'follow']);
        $this->exactly($pos, 1, 1);
        if ($this->ui->json) {
            throw new RuntimeException('Logs streaming does not support --json.');
        }
        $p = $this->registry->get($pos[0]);
        $lines = (string) ($opts['lines'] ?? '100');
        if (!preg_match('/^[1-9][0-9]{0,5}$/D', $lines)) {
            throw new RuntimeException('--lines must be a positive integer <= 999999');
        }
        $source = (string) ($opts['source'] ?? 'auto');
        if (!in_array($source, ['auto', 'journal', 'stdout', 'workerman', 'app'], true)) {
            throw new RuntimeException('Invalid logs source.');
        }
        $files = [
            'stdout' => $p['path'] . '/runtime/logs/stdout.log',
            'workerman' => $p['path'] . '/runtime/logs/workerman.log',
            'app' => $p['path'] . '/runtime/logs/webman.log',
        ];
        if ($source === 'auto') {
            $source = $p['mode'] === 'daemon' && is_file($files['stdout']) ? 'stdout' : 'journal';
        }
        if ($source === 'journal') {
            $cmd = [(string) (getenv('WM_JOURNALCTL') ?: '/usr/bin/journalctl'), '-u', $this->systemd->unitName($p['name']), '--no-pager', '-n', $lines];
        } else {
            if (!is_file($files[$source])) {
                throw new RuntimeException("Log file does not exist: {$files[$source]}");
            }
            $cmd = ['/usr/bin/tail', '-n', $lines, $files[$source]];
        }
        if (isset($opts['follow'])) {
            $cmd[] = '-f';
        }
        $result = Process::run($cmd, true);
        return $result['code'] === 0 ? 0 : 1;
    }

    /** @param list<string> $pos
     *  @param array<string,string|bool> $opts
     */
    private function import(array $pos, array $opts): int
    {
        $this->checkOptions($opts, ['recursive', 'dry-run', 'yes', 'user', 'php', 'mode', 'type']);
        $this->exactly($pos, 1, 1);
        $root = Runtime::canonicalDirectory($pos[0]);
        $directories = $this->scan($root, isset($opts['recursive']));
        $existing = $this->registry->all();
        $usedNames = array_column($existing, 'path', 'name');
        $usedPaths = array_column($existing, 'name', 'path');
        $found = [];
        $skipped = [];
        foreach ($directories as $dir) {
            if (isset($usedPaths[$dir])) {
                $skipped[] = "Already registered: {$dir}";
                continue;
            }
            $name = $this->suggestName($dir);
            $base = $name;
            $suffix = 2;
            while (isset($usedNames[$name])) {
                $name = substr($base, 0, 45) . '-' . $suffix++;
            }
            $settings = ['name' => $name, 'path' => $dir];
            foreach (['user' => 'user', 'php' => 'php', 'mode' => 'mode', 'type' => 'type'] as $option => $key) {
                if (isset($opts[$option])) {
                    $settings[$key] = $opts[$option];
                }
            }
            try {
                $project = Project::create($settings);
                $found[] = $project;
                $usedNames[$name] = $dir;
            } catch (Throwable $e) {
                $skipped[] = "{$dir}: {$e->getMessage()}";
            }
        }
        if (isset($opts['dry-run'])) {
            $this->ui->output(['found' => $found, 'skipped' => $skipped, 'dry_run' => true]);
            if (!$this->ui->json) {
                $this->ui->title('Import preview');
                $this->ui->table(['NAME', 'TYPE', 'PATH'], array_map(static fn (array $p): array => [$p['name'], $p['type'], $p['path']], $found));
                foreach ($skipped as $reason) {
                    $this->ui->warning($reason);
                }
            }
            return 0;
        }
        if ($found !== [] && !isset($opts['yes'])) {
            if ($this->nonInteractive || !$this->ui->interactive() || !$this->ui->confirm('Register ' . count($found) . ' project(s)?')) {
                throw new RuntimeException('Confirmation required; use --yes or preview with --dry-run.');
            }
        }
        $added = [];
        $errors = [];
        foreach ($found as $p) {
            try {
                $this->addProject($p, false, false);
                $added[] = $p['name'];
                $this->ui->ok("Imported {$p['name']}");
            } catch (Throwable $e) {
                $errors[$p['name']] = $e->getMessage();
            }
        }
        $this->ui->output(['ok' => $errors === [], 'added' => $added, 'skipped' => $skipped, 'errors' => $errors]);
        return $errors === [] ? 0 : 1;
    }

    /** @return list<string> */
    private function scan(string $root, bool $recursive): array
    {
        $results = [];
        $pending = [[$root, 0]];
        $ignored = ['.git', 'vendor', 'node_modules', 'runtime', 'cache', 'tests', 'test'];
        while ($pending !== []) {
            [$dir, $depth] = array_shift($pending);
            if (is_file($dir . '/start.php')) {
                $results[] = $dir;
                continue; // Never descend inside a project.
            }
            if (!$recursive || $depth >= 6) {
                continue;
            }
            foreach (scandir($dir) ?: [] as $name) {
                if ($name[0] === '.' || in_array($name, $ignored, true)) {
                    continue;
                }
                $path = $dir . '/' . $name;
                if (is_dir($path) && !is_link($path)) {
                    $pending[] = [$path, $depth + 1];
                }
            }
        }
        sort($results);
        return $results;
    }

    private function suggestName(string $path): string
    {
        $name = strtolower(basename(rtrim($path, '/')));
        $name = (string) preg_replace('/[^a-z0-9_-]+/', '-', $name);
        $name = (string) preg_replace('/^[^a-z]+/', '', $name);
        return substr($name, 0, 40) ?: 'project';
    }

    /** @param callable():void $fn */
    private function locked(callable $fn): void
    {
        Runtime::directory($this->registry->directory);
        $file = $this->registry->directory . '/.wm.lock';
        if (is_link($file)) {
            throw new RuntimeException('Refusing symlinked registry lock file');
        }
        $handle = fopen($file, 'c');
        if ($handle === false) {
            throw new RuntimeException("Cannot open registry lock: {$file}");
        }
        try {
            if (!flock($handle, LOCK_EX)) {
                throw new RuntimeException('Cannot acquire registry lock');
            }
            $fn();
        } finally {
            flock($handle, LOCK_UN);
            fclose($handle);
        }
    }

    private function menu(): int
    {
        while (true) {
            $this->listing([], []);
            $this->ui->line('  ' . $this->ui->color('[a]', '1;36') . ' Add project    '
                . $this->ui->color('[s]', '1;36') . ' Manage project    '
                . $this->ui->color('[r]', '1;36') . ' Refresh    '
                . $this->ui->color('[q]', '90') . ' Quit');
            $command = trim($this->ui->ask('Action', 'q'));
            if ($command === 'q') {
                return 0;
            }
            if ($command === 'r') {
                continue;
            }
            if ($command === 'a') {
                $this->add([], []);
                continue;
            }
            if ($command === 's') {
                $projects = array_column($this->registry->all(), 'name');
                $name = $this->ui->ask('Project name (' . implode(', ', $projects) . ')');
                if (!in_array($name, $projects, true)) {
                    $this->ui->warning('Unknown project');
                    continue;
                }
                $this->status([$name], [], true);
                $this->ui->line('  ' . $this->ui->color('start  stop  restart  reload', '1;32')
                    . '   ' . $this->ui->color('enable  disable', '1;36'));
                $action = $this->ui->ask('Action (Enter to return)');
                if (in_array($action, ['start', 'stop', 'restart', 'reload', 'enable', 'disable'], true)) {
                    $this->manage($action, [$name], []);
                }
                continue;
            }
            $this->ui->warning('Unknown action');
        }
    }
}
<?php

declare(strict_types=1);

namespace WM;

use RuntimeException;

final class Runtime
{
    public static function directory(string $path, int $mode = 0755): void
    {
        if (!is_dir($path) && !mkdir($path, $mode, true) && !is_dir($path)) {
            throw new RuntimeException("Unable to create directory: {$path}");
        }
    }

    public static function atomicWrite(string $file, string $contents, int $mode = 0644): void
    {
        self::directory(dirname($file));
        if (is_link($file)) {
            throw new RuntimeException("Refusing to overwrite symlink: {$file}");
        }
        $tmp = tempnam(dirname($file), '.wm-');
        if ($tmp === false) {
            throw new RuntimeException("Unable to prepare temporary file for {$file}");
        }
        try {
            if (file_put_contents($tmp, $contents, LOCK_EX) !== strlen($contents)) {
                throw new RuntimeException("Unable to write {$tmp}");
            }
            chmod($tmp, $mode);
            if (!rename($tmp, $file)) {
                throw new RuntimeException("Unable to replace {$file}");
            }
        } finally {
            if (file_exists($tmp)) {
                unlink($tmp);
            }
        }
    }

    public static function assertName(string $name): string
    {
        if (!preg_match('/^[a-z][a-z0-9_-]{0,47}$/D', $name)) {
            throw new RuntimeException('Invalid project name. Use 1β48 lowercase letters, digits, underscores or hyphens, starting with a letter.');
        }
        return $name;
    }

    public static function assertSafeValue(string $value, string $label): string
    {
        if ($value === '' || preg_match('/[\x00-\x1F\x7F]/', $value)) {
            throw new RuntimeException("Invalid {$label}: empty/control characters are prohibited");
        }
        return $value;
    }

    public static function canonicalFile(string $path): string
    {
        $resolved = realpath($path);
        if ($resolved === false || !is_file($resolved)) {
            throw new RuntimeException("File not found: {$path}");
        }
        return self::assertSafeValue($resolved, 'file');
    }

    public static function canonicalDirectory(string $path): string
    {
        $resolved = realpath($path);
        if ($resolved === false || !is_dir($resolved)) {
            throw new RuntimeException("Directory not found: {$path}");
        }
        return self::assertSafeValue($resolved, 'directory');
    }

    public static function validAbsolutePath(string $path, string $label): string
    {
        self::assertSafeValue($path, $label);
        if (!str_starts_with($path, '/') || preg_match('~(^|/)\.\.?(/|$)~', $path)) {
            throw new RuntimeException("{$label} must be an absolute path without . or .. segments");
        }
        return $path;
    }

    public static function resolveExecutable(string $php): string
    {
        if (!str_contains($php, '/')) {
            $path = (string) getenv('PATH');
            foreach (explode(PATH_SEPARATOR, $path) as $directory) {
                if ($directory !== '' && is_executable($directory . '/' . $php)) {
                    $php = $directory . '/' . $php;
                    break;
                }
            }
        }
        $php = self::canonicalFile($php);
        if (!is_executable($php)) {
            throw new RuntimeException("Not executable: {$php}");
        }
        return $php;
    }

    public static function canCreateWithin(string $directory): bool
    {
        $cursor = $directory;
        while (!file_exists($cursor)) {
            $parent = dirname($cursor);
            if ($parent === $cursor) {
                return false;
            }
            $cursor = $parent;
        }
        return is_dir($cursor) && is_writable($cursor);
    }

    public static function currentUser(): string
    {
        if (function_exists('posix_getpwuid')) {
            $info = posix_getpwuid(posix_geteuid());
            return (string) ($info['name'] ?? '');
        }
        return '';
    }

    public static function defaultUser(): string
    {
        $current = self::currentUser();
        if ($current !== '') {
            return $current;
        }
        throw new RuntimeException('Unable to detect the current user; provide --user USER.');
    }
}
<?php

declare(strict_types=1);

namespace WM;

use RuntimeException;

final class Registry
{
    public function __construct(public readonly string $directory)
    {
    }

    public function file(string $name): string
    {
        return $this->directory . '/' . Runtime::assertName($name) . '.json';
    }

    /** @return array<string,mixed> */
    public function get(string $name): array
    {
        $file = $this->file($name);
        if (is_link($file)) {
            throw new RuntimeException("Refusing symlinked project registry: {$file}");
        }
        if (!is_file($file)) {
            throw new RuntimeException("Project not registered: {$name}");
        }
        $data = json_decode((string) file_get_contents($file), true, 512, JSON_THROW_ON_ERROR);
        if (!is_array($data) || ($data['name'] ?? null) !== $name) {
            throw new RuntimeException("Corrupt project registry: {$file}");
        }
        return $data;
    }

    /** @return list<array<string,mixed>> */
    public function all(): array
    {
        $projects = [];
        foreach (glob($this->directory . '/*.json') ?: [] as $file) {
            if (is_link($file)) {
                throw new RuntimeException("Refusing symlinked project config: {$file}");
            }
            $name = basename($file, '.json');
            $projects[] = $this->get($name);
        }
        usort($projects, fn (array $a, array $b): int => strcmp($a['name'], $b['name']));
        return $projects;
    }

    /** @param array<string,mixed> $project */
    public function put(array $project): void
    {
        Runtime::atomicWrite($this->file((string) $project['name']), json_encode($project, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR) . "\n", 0644);
    }

    public function remove(string $name): void
    {
        $file = $this->file($name);
        if (is_file($file) && !unlink($file)) {
            throw new RuntimeException("Cannot remove project config: {$file}");
        }
    }
}
<?php

declare(strict_types=1);

namespace WM;

use RuntimeException;

final class Project
{
    public static function detectType(string $path): ?string
    {
        $composer = $path . '/composer.json';
        if (is_file($composer)) {
            $config = json_decode((string) file_get_contents($composer), true);
            $requires = is_array($config) ? array_merge($config['require'] ?? [], $config['require-dev'] ?? []) : [];
            if (isset($requires['workerman/webman']) || isset($requires['workerman/webman-framework']) || isset($requires['webman/webman'])) {
                return 'webman';
            }
            if (isset($requires['workerman/workerman']) || isset($requires['workerman/gateway-worker'])) {
                return 'workerman';
            }
        }
        if (is_file($path . '/config/server.php') && is_dir($path . '/app')) {
            return 'webman';
        }
        if (is_dir($path . '/vendor/workerman/webman') || is_dir($path . '/vendor/workerman/webman-framework')) {
            return 'webman';
        }
        if (is_dir($path . '/vendor/workerman/workerman')) {
            return 'workerman';
        }
        return null;
    }

    /** @param array<string,mixed> $settings
     *  @return array<string,mixed>
     */
    public static function create(array $settings): array
    {
        $name = Runtime::assertName((string) ($settings['name'] ?? ''));
        $path = Runtime::canonicalDirectory((string) ($settings['path'] ?? ''));
        $type = (string) ($settings['type'] ?? self::detectType($path) ?? '');
        if (!in_array($type, ['webman', 'workerman'], true)) {
            throw new RuntimeException('Cannot detect framework. Specify --type webman|workerman.');
        }
        $mode = (string) ($settings['mode'] ?? ($type === 'webman' ? 'daemon' : 'foreground'));
        if (!in_array($mode, ['daemon', 'foreground'], true)) {
            throw new RuntimeException('Mode must be daemon or foreground.');
        }
        $entry = (string) ($settings['entry'] ?? 'start.php');
        Runtime::assertSafeValue($entry, 'entry');
        if (str_starts_with($entry, '/') || str_starts_with($entry, '-') || preg_match('~(^|/)\.\.?(/|$)~', $entry)) {
            throw new RuntimeException('Entry must be a relative PHP file within the project.');
        }
        $file = Runtime::canonicalFile($path . '/' . $entry);
        if (!str_starts_with($file, rtrim($path, '/') . '/') || pathinfo($file, PATHINFO_EXTENSION) !== 'php') {
            throw new RuntimeException('Entry must resolve to a PHP file inside the project.');
        }
        $entry = substr($file, strlen(rtrim($path, '/')) + 1);
        $php = Runtime::resolveExecutable((string) ($settings['php'] ?? 'php'));
        $user = (string) ($settings['user'] ?? Runtime::defaultUser());
        if (!preg_match('/^[a-z_][a-z0-9_-]*\$?$/iD', $user)) {
            throw new RuntimeException('Invalid Linux user name.');
        }
        if (function_exists('posix_getpwnam') && posix_getpwnam($user) === false) {
            throw new RuntimeException("Linux user does not exist: {$user}");
        }
        $pidFile = $settings['pid_file'] ?? null;
        if ($mode === 'daemon') {
            if ($pidFile === null && $type === 'webman') {
                $pidFile = $path . '/runtime/webman.pid';
            }
            if (!is_string($pidFile)) {
                throw new RuntimeException('Workerman daemon mode requires --pid-file matching Worker::$pidFile in your project.');
            }
            $pidFile = Runtime::validAbsolutePath($pidFile, 'PID file');
        } else {
            $pidFile = null;
        }
        return [
            'name' => $name,
            'type' => $type,
            'path' => $path,
            'entry' => $entry,
            'php' => $php,
            'user' => $user,
            'mode' => $mode,
            'pid_file' => $pidFile,
            'created_at' => gmdate('c'),
        ];
    }

    /** @param array<string,mixed> $project */
    public static function existingPid(array $project): ?int
    {
        $file = $project['pid_file'] ?? null;
        if (!is_string($file) || !is_file($file)) {
            return null;
        }
        $pidText = trim((string) @file_get_contents($file));
        if (!preg_match('/^[1-9][0-9]*$/D', $pidText)) {
            return null;
        }
        $pid = (int) $pidText;
        if ($pid <= 1 || !function_exists('posix_kill')) {
            return null;
        }
        return @posix_kill($pid, 0) || (function_exists('posix_get_last_error') && posix_get_last_error() === 1) ? $pid : null;
    }
}
<?php

declare(strict_types=1);

namespace WM;

use RuntimeException;

final class Systemd
{
    public const MARKER = '# Managed by WM; generated automatically; do not edit. Keep changes in /etc/wm/projects.d.';

    public function __construct(public readonly string $unitDirectory, private readonly string $executable = '/usr/bin/systemctl')
    {
    }

    public function unitName(string $name): string
    {
        return 'wm-' . Runtime::assertName($name) . '.service';
    }

    public function unitPath(string $name): string
    {
        return $this->unitDirectory . '/' . $this->unitName($name);
    }

    private static function escape(string $value): string
    {
        Runtime::assertSafeValue($value, 'systemd value');
        return str_replace(['\\', '"', '%', '$'], ['\\\\', '\\"', '%%', '$$'], $value);
    }

    private static function token(string $value): string
    {
        return '"' . self::escape($value) . '"';
    }

    /** @param array<string,mixed> $p */
    public function render(array $p): string
    {
        $name = Runtime::assertName((string) $p['name']);
        $type = $p['mode'] === 'daemon' ? 'forking' : 'exec';
        $command = self::token((string) $p['php']) . ' ' . self::token((string) $p['entry']) . ' start';
        if ($type === 'forking') {
            $command .= ' -d';
        }
        $pid = $type === 'forking' ? 'PIDFile=' . self::pathEscape((string) $p['pid_file']) . "\n" : '';
        return self::MARKER . "\n" . (<<<UNIT
[Unit]
Description=WM managed {$name} ({$p['type']})
After=network-online.target
Wants=network-online.target
StartLimitIntervalSec=60
StartLimitBurst=5

[Service]
Type={$type}
User={$p['user']}
WorkingDirectory={$this->workingDirectory($p['path'])}
ExecStart={$command}
ExecReload=/bin/kill -USR1 \$MAINPID
{$pid}Restart=on-failure
RestartSec=5s
KillSignal=SIGINT
KillMode=mixed
TimeoutStopSec=45s
LimitNOFILE=65535
StandardOutput=journal
StandardError=journal

[Install]
WantedBy=multi-user.target
UNIT
        ) . "\n";

    }

    private static function pathEscape(string $path): string
    {
        Runtime::validAbsolutePath($path, 'systemd path');
        // Paths are directive values, not Exec* arguments: no $-substitution.
        // Encode whitespace and quoting characters as systemd C escapes.
        return str_replace(['\\', ' ', '"', '%', '#'], ['\\\\', '\\x20', '\\x22', '%%', '\\x23'], $path);
    }

    private function workingDirectory(string $path): string
    {
        return self::pathEscape($path);
    }

    public function unitOwned(string $name): bool
    {
        $file = $this->unitPath($name);
        if (is_link($file)) {
            throw new RuntimeException("Refusing symlinked unit: {$file}");
        }
        if (!is_file($file)) {
            return false;
        }
        return str_starts_with((string) file_get_contents($file), self::MARKER);
    }

    /** @param array<string,mixed> $p */
    public function install(array $p): void
    {
        $file = $this->unitPath($p['name']);
        if ((is_file($file) || is_link($file)) && !$this->unitOwned($p['name'])) {
            throw new RuntimeException("Refusing to overwrite unmanaged service unit: {$file}");
        }
        Runtime::atomicWrite($file, $this->render($p));
    }

    public function remove(string $name): void
    {
        $file = $this->unitPath($name);
        if (is_file($file) || is_link($file)) {
            if (!$this->unitOwned($name)) {
                throw new RuntimeException("Refusing to delete unmanaged service unit: {$file}");
            }
            if (!unlink($file)) {
                throw new RuntimeException("Cannot delete service unit: {$file}");
            }
        }
    }

    /** @param list<string> $args */
    public function call(array $args, bool $stream = false): array
    {
        return Process::run(array_merge([$this->executable], $args), $stream);
    }

    public function reload(): void
    {
        $this->must(['daemon-reload']);
    }

    /** @param list<string> $args */
    public function must(array $args): string
    {
        $result = $this->call($args);
        if ($result['code'] !== 0) {
            throw new RuntimeException('systemctl ' . implode(' ', $args) . ': ' . trim($result['stderr'] ?: $result['stdout']));
        }
        return $result['stdout'];
    }

    /** @return array<string,string> */
    public function show(string $name): array
    {
        $result = $this->call(['show', $this->unitName($name), '--no-pager', '--property=LoadState,ActiveState,SubState,MainPID,UnitFileState,ActiveEnterTimestamp,NeedDaemonReload']);
        if ($result['code'] !== 0) {
            return ['ActiveState' => 'unknown', 'LoadState' => 'unknown', 'error' => trim($result['stderr'])];
        }
        $properties = [];
        foreach (explode("\n", $result['stdout']) as $line) {
            if (str_contains($line, '=')) {
                [$k, $v] = explode('=', $line, 2);
                $properties[$k] = $v;
            }
        }
        return $properties;
    }
}
<?php

declare(strict_types=1);

namespace WM;

use RuntimeException;

final class Process
{
    /** @param list<string> $argv
     *  @return array{code:int,stdout:string,stderr:string}
     */
    public static function run(array $argv, bool $stream = false): array
    {
        if ($argv === [] || !is_string($argv[0])) {
            throw new RuntimeException('Invalid command');
        }
        $pipes = [];
        $proc = @proc_open($argv, [0 => ['file', '/dev/null', 'r'], 1 => ['pipe', 'w'], 2 => ['pipe', 'w']], $pipes, null, null, ['bypass_shell' => true]);
        if (!is_resource($proc)) {
            throw new RuntimeException('Cannot launch command: ' . $argv[0]);
        }
        stream_set_blocking($pipes[1], false);
        stream_set_blocking($pipes[2], false);
        $out = '';
        $err = '';
        try {
            while (true) {
                $read = [];
                foreach ([1, 2] as $i) {
                    if (!feof($pipes[$i])) {
                        $read[] = $pipes[$i];
                    }
                }
                if ($read === []) {
                    break;
                }
                $write = null;
                $except = null;
                $ready = @stream_select($read, $write, $except, 1, 0);
                if ($ready === false) {
                    break;
                }
                if ($ready === 0) {
                    continue;
                }
                foreach ($read as $handle) {
                    $chunk = fread($handle, 8192);
                    if ($chunk === false || $chunk === '') {
                        continue;
                    }
                    if ($handle === $pipes[1]) {
                        $out .= $stream ? '' : $chunk;
                        if ($stream) {
                            fwrite(STDOUT, $chunk);
                        }
                    } else {
                        $err .= $stream ? '' : $chunk;
                        if ($stream) {
                            fwrite(STDERR, $chunk);
                        }
                    }
                }
            }
        } finally {
            fclose($pipes[1]);
            fclose($pipes[2]);
        }
        $code = proc_close($proc);
        return ['code' => $code, 'stdout' => $out, 'stderr' => $err];
    }
}
<?php

declare(strict_types=1);

namespace WM;

/** A small, dependency-free terminal renderer; never takes over the screen. */
final class UI
{
    public function __construct(public readonly bool $ansi, public readonly bool $json)
    {
    }

    public function color(string $text, string $code): string
    {
        return $this->ansi ? "\033[{$code}m{$text}\033[0m" : $text;
    }

    public function title(string $heading): void
    {
        if (!$this->json) {
            echo "\n" . $this->color('β', '1;36') . ' ' . $this->color($heading, '1') . "\n\n";
        }
    }

    public function section(string $heading): void
    {
        if (!$this->json) {
            echo '  ' . $this->color(strtoupper($heading), '1;90') . "\n";
        }
    }

    public function keyValue(string $label, string $value, ?string $style = null): void
    {
        if (!$this->json) {
            echo '  ' . $this->color(str_pad($label, 22), '90') . ($style ? $this->color($value, $style) : $value) . "\n";
        }
    }

    public function ok(string $message): void
    {
        if (!$this->json) {
            echo '  ' . $this->color('β', '1;32') . " {$message}\n";
        }
    }

    public function warning(string $message): void
    {
        if (!$this->json) {
            echo '  ' . $this->color('!', '1;33') . " {$message}\n";
        }
    }

    public function line(string $message = ''): void
    {
        if (!$this->json) {
            echo $message . "\n";
        }
    }

    public function output(mixed $data): void
    {
        if ($this->json) {
            echo json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR) . "\n";
        }
    }

    /** Run state and boot policy use different symbols AND colors. */
    public function stateLabel(string $state): string
    {
        return match ($state) {
            'active' => 'β active',
            'inactive' => 'β inactive',
            'activating' => 'β activating',
            'deactivating' => 'β stopping',
            'reloading' => 'β» reloading',
            'failed' => 'β failed',
            default => 'β ' . $state,
        };
    }

    public function stateStyle(string $state): string
    {
        return match ($state) {
            'active' => '1;32',  // green: currently running
            'failed' => '1;31',  // red: failed
            'activating', 'deactivating' => '1;33',
            'reloading' => '1;35',
            default => '90',     // gray: stopped/unknown
        };
    }

    public function bootLabel(string $boot): string
    {
        return match ($boot) {
            'enabled' => 'β enabled',
            'enabled-runtime' => 'β enabled*',
            'disabled' => 'β disabled',
            'masked', 'masked-runtime' => 'β masked',
            'static' => 'β static',
            'indirect' => 'β indirect',
            default => 'β ' . $boot,
        };
    }

    public function bootStyle(string $boot): string
    {
        return match ($boot) {
            'enabled', 'enabled-runtime' => '1;36', // cyan: starts on boot, independent of running
            'masked', 'masked-runtime' => '1;31',
            'static', 'indirect', 'linked', 'linked-runtime' => '33',
            default => '90',
        };
    }

    public function projectSummary(int $total, int $running, int $enabled, int $failed): void
    {
        if ($this->json) {
            return;
        }
        $parts = [
            $this->color($total . ' projects', '1'),
            $this->color('β ' . $running . ' active', '1;32'),
            $this->color('β ' . $enabled . ' enabled', '1;36'),
        ];
        if ($failed > 0) {
            $parts[] = $this->color('β ' . $failed . ' failed', '1;31');
        }
        echo '  ' . implode($this->color('   Β·   ', '90'), $parts) . "\n\n";
    }

    /** Visible terminal width. COLUMNS is the portable, non-invasive override. */
    public function terminalWidth(): int
    {
        $columns = getenv('COLUMNS');
        if (is_string($columns) && ctype_digit($columns) && (int) $columns >= 40 && (int) $columns <= 1000) {
            return (int) $columns;
        }
        return 116;
    }

    private function visibleWidth(string $text): int
    {
        if (function_exists('mb_strwidth')) {
            return mb_strwidth($text, 'UTF-8');
        }
        $chars = preg_split('//u', $text, -1, PREG_SPLIT_NO_EMPTY);
        if ($chars === false) {
            return strlen($text);
        }
        $width = 0;
        foreach ($chars as $char) {
            $width += preg_match('/[\p{Han}\p{Hiragana}\p{Katakana}\p{Hangul}\x{FF01}-\x{FF60}\x{FFE0}-\x{FFE6}]/u', $char) ? 2 : 1;
        }
        return $width;
    }

    private function clip(string $text, int $maxWidth): string
    {
        if ($this->visibleWidth($text) <= $maxWidth) {
            return $text;
        }
        $chars = preg_split('//u', $text, -1, PREG_SPLIT_NO_EMPTY);
        if ($chars === false) {
            return substr($text, 0, max(0, $maxWidth - 3)) . '...';
        }
        $result = '';
        $width = 0;
        foreach ($chars as $char) {
            $next = $this->visibleWidth($char);
            if ($width + $next > $maxWidth - 1) {
                break;
            }
            $result .= $char;
            $width += $next;
        }
        return $result . 'β¦';
    }

    /** @param list<string> $columns
     *  @param list<list<string>> $rows
     *  @param array<int,array<int,string>> $styles ANSI styles keyed by row, then column
     */
    public function table(array $columns, array $rows, array $styles = []): void
    {
        if ($this->json || $columns === []) {
            return;
        }
        $widths = [];
        foreach ($columns as $i => $column) {
            $widths[$i] = max(6, $this->visibleWidth($column));
            foreach ($rows as $row) {
                $widths[$i] = min(52, max($widths[$i], $this->visibleWidth($row[$i] ?? '')));
            }
        }
        $available = max(40, $this->terminalWidth() - 4);
        $overhead = (count($widths) - 1) * 3;
        $minWidths = array_map(fn (int $i): int => max(6, $this->visibleWidth($columns[$i])), array_keys($widths));
        // Reduce the widest flexible cell first, preserving column headings and status labels.
        while (array_sum($widths) + $overhead > $available) {
            $candidate = null;
            foreach ($widths as $i => $width) {
                if ($width <= $minWidths[$i]) {
                    continue;
                }
                if ($candidate === null || $width > $widths[$candidate]) {
                    $candidate = $i;
                }
            }
            if ($candidate === null) {
                break;
            }
            --$widths[$candidate];
        }
        $render = function (array $cells, array $cellStyles = []) use ($widths): string {
            $parts = [];
            foreach ($cells as $i => $cell) {
                $visible = $this->clip($cell, $widths[$i]);
                $padded = $visible . str_repeat(' ', max(0, $widths[$i] - $this->visibleWidth($visible)));
                $parts[] = isset($cellStyles[$i]) ? $this->color($padded, $cellStyles[$i]) : $padded;
            }
            return '  ' . implode('   ', $parts);
        };
        echo $this->color($render($columns), '1;90') . "\n";
        echo $this->color('  ' . str_repeat('β', array_sum($widths) + $overhead), '90') . "\n";
        foreach ($rows as $index => $row) {
            echo $render($row, $styles[$index] ?? []) . "\n";
        }
        if ($rows === []) {
            echo $this->color('  (no projects)', '90') . "\n";
        }
        echo "\n";
    }

    public function interactive(): bool
    {
        return function_exists('stream_isatty') && stream_isatty(STDIN);
    }

    public function ask(string $question, ?string $default = null): string
    {
        $suffix = $default !== null && $default !== '' ? " [{$default}]" : '';
        echo $this->color('  βΊ ', '1;36') . $question . $this->color($suffix, '90') . ': ';
        $value = trim((string) fgets(STDIN));
        return $value === '' ? (string) $default : $value;
    }

    public function confirm(string $question, bool $default = false): bool
    {
        $value = strtolower($this->ask($question . ($default ? ' [Y/n]' : ' [y/N]')));
        if ($value === '') {
            return $default;
        }
        return in_array($value, ['y', 'yes'], true);
    }
}
­7ε[α_Oc!ύΦ«6ΩχΧdκFB©L   GBMB