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

declare(strict_types=1);

use Ep\Console\Application;
use Ep\Console\ArgvInput;

(static function (): void {
    $cwd = getcwd();

    if (file_exists($cwd . '/ep.json')) {
        $options = json_decode(file_get_contents($cwd . '/ep.json'), true);
    } else {
        $message = "Could not find a ep.json file in {$cwd}" . PHP_EOL;
        fwrite(STDERR, $message);
        exit(1);
    }
    require($options['bootstrap']);
    unset($options['bootstrap']);

    if (!file_exists($options['config'])) {
        $message = "Unable to find config file in {$options['config']}" . PHP_EOL;
        fwrite(STDERR, $message);
        exit(1);
    }

    Ep::init(array_merge(
        $userConfig = require($options['config']),
        [
            'rootNamespace' => 'Ep',
            'commandSuffix' => 'Command',
            'actionSuffix' => 'Action',
            'defaultAction' => 'index'
        ]
    ));
    unset($options['config']);

    $options['common'] ??= [];
    $options['common']['userRootNamespace'] = $userConfig['rootNamespace'] ?? 'App';

    $input = new ArgvInput();
    foreach ($options as $name => $value) {
        $input->setOption($name, $value);
    }

    $exitCode = Ep::getDi()
        ->get(Application::class)
        ->run($input);

    exit($exitCode);
})();
