#!/usr/bin/env php
<?php
/*
 * This file is part of the Artemeon Core - Web Application Framework.
 *
 * (c) Artemeon <www.artemeon.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

(new class() {
    protected string $name;
    protected string $version;

    public function main()
    {
        $this->autoload();
        $this->fetchVersion();

        $configValues = (new \Artemeon\M2G\Config\ConfigReader())->read();
        $githubConnector = new \Artemeon\M2G\Service\GithubConnector($configValues);
        $mantisConnector = new \Artemeon\M2G\Service\MantisConnector($configValues);

        $app = new \Symfony\Component\Console\Application($this->name, $this->version);
        $app->add(new \Artemeon\M2G\Command\ConfigurationCommand($githubConnector));
        $app->add(new \Artemeon\M2G\Command\ReadMantisIssueCommand($mantisConnector));
        $app->add(new \Artemeon\M2G\Command\ReadGithubIssueCommand($githubConnector));
        $app->add(new \Artemeon\M2G\Command\CreateGithubIssueFromMantisIssue($mantisConnector, $githubConnector));
        $app->run();
    }

    protected function autoload()
    {
        if (isset($GLOBALS['_composer_autoload_path'])) {
            define('COMPOSER_INSTALL_PATH', $GLOBALS['_composer_autoload_path']);

            unset($GLOBALS['_composer_autoload_path']);
        } else {
            foreach ([__DIR__ . '/../../autoload.php', __DIR__ . '/../vendor/autoload.php', __DIR__ . '/vendor/autoload.php'] as $file) {
                if (file_exists($file)) {
                    define('COMPOSER_INSTALL_PATH', $file);

                    break;
                }
            }

            unset($file);
        }

        require COMPOSER_INSTALL_PATH;
    }

    protected function fetchVersion()
    {
        $packageJson = json_decode(file_get_contents(__DIR__ . '/composer.json'), true);

        $name = $packageJson['name'] ?? null;
        $this->name = explode('/', $name)[1] ?? null;

        foreach ([__DIR__ . '/../../composer/installed.php', __DIR__ . '/../vendor/composer/installed.php', __DIR__ . '/vendor/composer/installed.php'] as $file) {
            if (file_exists($file)) {
                $installed = require $file;
                $this->version = $installed['versions'][$name]['pretty_version'] ?? null;

                break;
            }
        }
    }
})->main();





