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

declare(strict_types=1);

const BASE_DIR = __DIR__ . '/../../../../';

require BASE_DIR . '/vendor/autoload.php';

use apexl\Io\Client;
use apexl\Io\collections\DaedalusCommandCollection;
use apexl\Io\includes\Hook;
use apexl\Io\includes\System;
use Symfony\Component\Console\Application as ConsoleApplication;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Component\Console\Output\ConsoleOutput;

$keepArgs = array_slice($_SERVER['argv'], 0, 1);

foreach ($_SERVER['argv'] as $ix => $arg) {
    if ($arg === '-c' || $arg === '--config') {
        $keepArgs[] = $_SERVER['argv'][$ix];
        $keepArgs[] = $_SERVER['argv'][$ix + 1];
        break;
    }
}


$input = new ArgvInput(
    $keepArgs, new \Symfony\Component\Console\Input\InputDefinition([
            new \Symfony\Component\Console\Input\InputArgument(
                'any',
                \Symfony\Component\Console\Input\InputArgument::IS_ARRAY,
            ),
            new \Symfony\Component\Console\Input\InputOption(
                'config',
                'c',
                \Symfony\Component\Console\Input\InputOption::VALUE_OPTIONAL,
                default: null
            ),
        ]
    )
);

$output = new ConsoleOutput();

$config = $input->getOption('config') ?? null;

try {
    $ioApp = Client::getInstance();

    if ($config) {
        if (!file_exists($config)) {
            throw new Exception(sprintf('Config file does not exist: %s', $config));
        }

        $ioApp->setConfigFile($config);
    } else {
        $ioApp->setConfigDir(BASE_DIR . '/config');
    }

    $ioApp->setBasePath(BASE_DIR . '/web');

    $ioApp->bootstrap();

    $console = new ConsoleApplication();

    /** @var DaedalusCommandCollection $commands */
    $commands = Hook::processHook('consoleCommands', new DaedalusCommandCollection());
    $commands->map(System::getRegisteredService(...))->each($console->add(...));

    return $console->run();
} catch (Exception $e) {
    $output->writeln(sprintf('<error>%s</error>', $e->getMessage()));

    return Command::FAILURE;
}
