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

declare(strict_types=1);

use Buggregator\Trap\Command;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\CommandLoader\FactoryCommandLoader;

if ('cli' !== PHP_SAPI) {
    throw new Exception('This script must be run from the command line.');
}

(static function () {
    $cwd = \getcwd();

    $possibleAutoloadPaths = [
        // local dev repository
        \dirname(__DIR__) . '/vendor/autoload.php',
        // running from project root
        $cwd . '/vendor/autoload.php',
        // running from project bin
        \dirname($cwd) . '/autoload.php',
        // dependency
        \dirname(__DIR__, 4) . '/vendor/autoload.php',
    ];
    $autoloadPath = null;
    foreach ($possibleAutoloadPaths as $possibleAutoloadPath) {
        if (\file_exists($possibleAutoloadPath)) {
            $autoloadPath = $possibleAutoloadPath;
            break;
        }
    }

    if ($autoloadPath === null) {
        $message = "Unable to find `vendor/autoload.php` in the following paths:\n\n";
        $message .= '- ' . \implode("\n- ", $possibleAutoloadPaths) . "\n\n";
        \fwrite(STDERR, $message);
        exit(1);
    }

    require_once $autoloadPath;

    $application = new Application();
    $application->setCommandLoader(
        new FactoryCommandLoader([
            Command\Run::getDefaultName() => static fn() => new Command\Run(),
            Command\Joke::getDefaultName() => static fn() => new Command\Joke(),
            Command\Test::getDefaultName() => static fn() => new Command\Test(),
        ]),
    );
    $application->setDefaultCommand(Command\Run::getDefaultName(), false);
    $application->run();
})();
