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

declare(strict_types=1);

use Composer\Factory as ComposerFactory;
use Composer\IO\ConsoleIO;
use Chiron\Dev\Tools\Composer\DevToolsPlugin;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Helper\HelperSet;
use Symfony\Component\Console\Helper\QuestionHelper;
use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Component\Console\Input\StringInput;

(static function (array $argv): void {
    $composerAutoloadLocations = [
        __DIR__ . '/../autoload.php',
        __DIR__ . '/../vendor/autoload.php',
        __DIR__ . '/../../../autoload.php',
    ];

    foreach ($composerAutoloadLocations as $file) {
        if (file_exists($file)) {
            $composerAutoloader = $file;

            break;
        }
    }
    unset($file);

    if (! isset($composerAutoloader)) {
        fwrite(
            STDERR,
            'To execute this command, please install Composer and run \'composer install\'.' . PHP_EOL
            . 'For more information, go to https://getcomposer.org' . PHP_EOL,
        );

        exit(1);
    }

    require $composerAutoloader;

    $input = new StringInput('');
    //$input->setInteractive(false);
    $output = ComposerFactory::createOutput();
    $helperSet = new HelperSet([new QuestionHelper()]);
    $io = new ConsoleIO($input, $output, $helperSet);

    $composer = ComposerFactory::create($io);
    $composerPlugin = new DevToolsPlugin();
    $composerPlugin->activate($composer, $io);

    $application = new Application('chiron/devtools');
    $application->addCommands($composerPlugin->getCommands());
    $application->run(new ArgvInput($argv));
})($argv);
