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

declare(strict_types=1);

use NewCMS\Core\Console\Application;
use NewCMS\Core\Kernel\Config;
use NewCMS\Core\Kernel\Kernel;

if (PHP_SAPI !== 'cli') {
    echo 'bin/console must be run from the command line.', PHP_EOL;

    exit(1);
}

$projectDir = \dirname(__DIR__);

if (!is_file($autoload = $projectDir . '/vendor/autoload.php')) {
    fwrite(STDERR, "Dependencies are missing. Run: composer install\n");

    exit(1);
}

/** @var Composer\Autoload\ClassLoader $classLoader */
$classLoader = require $autoload;

// --env / --no-debug are consumed before boot: they decide which compiled
// container is loaded, so they cannot wait for the console component.
$overrides = [];

foreach ($argv as $argument) {
    if (preg_match('/^--env=(.+)$/', (string) $argument, $matches) === 1) {
        $overrides['env'] = $matches[1];
        $overrides['debug'] = $matches[1] !== 'prod';
    }

    if ($argument === '--no-debug') {
        $overrides['debug'] = false;
    }
}

$config = Config::fromFile($projectDir . '/config/config.php');

if ($overrides !== []) {
    $config = $config->with($overrides);
}

$kernel = new Kernel($projectDir, $config, $classLoader);

/** @var Application $application */
$application = $kernel->getContainer()->get('console.application');

exit($application->run());
