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

declare(strict_types=1);

use apexl\Io\Client;
use apexl\Io\collections\DaedalusCommandCollection;
use apexl\Io\factories\ClientFactory;
use apexl\Io\factories\ContainerFactory;
use apexl\Io\includes\HookManager;
use apexl\Io\services\FilePaths;
use DI\Bridge\Slim\Bridge;
use DI\Container;
use Dotenv\Dotenv;
use Symfony\Component\Console\Application as ConsoleApplication;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Output\ConsoleOutput;

$composerPath = realpath($GLOBALS['_composer_autoload_path']);
require $composerPath;
$baseDir = realpath(dirname($composerPath) . '/..');
Dotenv::createImmutable($baseDir)->load();

$output = new ConsoleOutput();

try {
  $application = Bridge::create(new ContainerFactory()->make($baseDir));

  /** @var Container $container */
  $container = $application->getContainer();

  $container->set(FilePaths::class, new FilePaths($baseDir));

  $client = $container->get(ClientFactory::class)->make();

  $container->set(Client::class, $client);
  $client->bootstrap();

  $console = new ConsoleApplication();

  $container->get(HookManager::class)->processHook('consoleCommands', new DaedalusCommandCollection())
      ->map($container->get(...))
      ->each($console->add(...));

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

  return Command::FAILURE;
}
