#!/usr/bin/env php
<?php

/**
 * @deprecated To be removed with Shlink 3.0.0
 * This script is provided to keep backwards compatibility on how to run shlink with swoole while being still able to
 * update to mezzio/mezzio-swoole 3.x
 */

declare(strict_types=1);

namespace Mezzio\Swoole\Command;

use Laminas\ServiceManager\ServiceManager;
use PackageVersions\Versions;
use Symfony\Component\Console\Application as CommandLine;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\CommandLoader\ContainerCommandLoader;

use function explode;
use function Functional\filter;
use function str_starts_with;
use function strstr;

/** @var ServiceManager $container */
$container = require __DIR__ . '/../../config/container.php';
$version = strstr(Versions::getVersion('mezzio/mezzio-swoole'), '@', true);
$commandsPrefix = 'mezzio:swoole:';
$commands = filter(
    $container->get('config')['laminas-cli']['commands'] ?? [],
    fn ($c, string $command) => str_starts_with($command, $commandsPrefix),
);
$registeredCommands = [];

foreach ($commands as $newName => $commandServiceName) {
    [, $oldName] = explode($commandsPrefix, $newName);
    $registeredCommands[$oldName] = $commandServiceName;

    $container->addDelegator($commandServiceName, static function ($c, $n, callable $factory) use ($oldName) {
        /** @var Command $command */
        $command = $factory();
        $command->setAliases([$oldName]);

        return $command;
    });
}

$commandLine = new CommandLine('Mezzio web server', $version);
$commandLine->setAutoExit(true);
$commandLine->setCommandLoader(new ContainerCommandLoader($container, $registeredCommands));
$commandLine->run();
