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

declare(strict_types=1);

use Composer\InstalledVersions;
use HeptaConnect\Production\DevOps\Kernel\HttpKernel;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Component\Console\Input\ArgvInput;

use function HeptaConnect\Production\getPluginLoader;

$_SERVER['APP_RUNTIME_OPTIONS']['use_putenv'] = true;
$projectRoot = \dirname(__DIR__);

if (
    !\file_exists($projectRoot . '/.env')
    && !\file_exists($projectRoot . '/.env.dist')
    && !\file_exists($projectRoot . '/.env.local')
    && !\file_exists($projectRoot . '/.env.local.php')
) {
    $_SERVER['APP_RUNTIME_OPTIONS']['disable_dotenv'] = true;
}

require_once __DIR__ . '/../vendor/autoload_runtime.php';
$classLoader = require __DIR__ . '/../vendor/autoload.php';
require_once __DIR__ . '/../config/plugin-loader.php';

return function (array $context) use ($classLoader, $projectRoot): Application {
    if (!isset($context['PROJECT_ROOT'])) {
        $context['PROJECT_ROOT'] = $projectRoot;
    }

    $input = new ArgvInput();
    $env = $input->getParameterOption(['--env', '-e'], $context['APP_ENV'] ?? 'prod', true);
    $debug = ($context['APP_DEBUG'] ?? ($env !== 'prod')) && !$input->hasParameterOption('--no-debug', true);

    if ($input->getFirstArgument() === 'system:install') {
        $context['INSTALL'] = true;
    }

    if (\trim($context['DATABASE_URL'] ?? '') === '' || isset($context['INSTALL'])) {
        $context['SHOPWARE_SKIP_CONNECTION_VARIABLES'] = true;
    }

    $httpKernel = new HttpKernel($env, $debug, $classLoader);
    $httpKernel->setPluginLoader(getPluginLoader($projectRoot, $classLoader));
    $kernel = $httpKernel->getKernel();

    $application = new Application($kernel);
    $application->setName('HEPTAconnect');

    if (InstalledVersions::isInstalled('heptacom/heptaconnect-framework')) {
        $application->setVersion(InstalledVersions::getVersion('heptacom/heptaconnect-framework'));
    } elseif (InstalledVersions::isInstalled('heptacom/heptaconnect-core')) {
        $application->setVersion(InstalledVersions::getVersion('heptacom/heptaconnect-core'));
    } else {
        $application->setVersion('UNKNOWN');
    }

    $kernel->boot();

    return $application;
};
