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

use Artemeon\M2G\Command\ConfigurationCommand;
use Artemeon\M2G\Command\CreateGithubIssueFromMantisIssue;
use Artemeon\M2G\Command\ReadGithubIssueCommand;
use Artemeon\M2G\Command\ReadMantisIssueCommand;
use Artemeon\M2G\Config\ConfigReader;
use Artemeon\M2G\Helper\VersionHelper;
use Artemeon\M2G\Service\GithubConnector;
use Artemeon\M2G\Service\MantisConnector;
use Symfony\Component\Console\Application;

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

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

        $configValues = (new ConfigReader())->read();
        $githubConnector = new GithubConnector($configValues);
        $mantisConnector = new MantisConnector($configValues);

        $app = new Application($this->name, $this->version);
        $app->add(new ConfigurationCommand());
        $app->add(new ReadMantisIssueCommand($mantisConnector));
        $app->add(new ReadGithubIssueCommand($githubConnector));
        $app->add(new 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;

        $this->version = VersionHelper::fetchVersion();
    }
})->main();
