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

use Innmind\Signals\Info;
use Innmind\Signals\Signal;
use Ninja\Cosmic\Application\Application;
use Ninja\Cosmic\Environment\Env;
use Ninja\Cosmic\Environment\Exception\EnvironmentNotFoundException;
use Ninja\Cosmic\Event\Lifecycle;
use Ninja\Cosmic\Signal\SignalHandler;
use Ninja\Cosmic\Terminal\Terminal;
use Ninja\Cosmic\Terminal\Theme\ThemeInterface;

use function Cosmic\find_env;
use function Cosmic\is_phar;

if (false === in_array(PHP_SAPI, ['cli', 'phpdbg', 'embed'], true)) {
    echo PHP_EOL . 'This app may only be invoked from a command line, got "' . PHP_SAPI . '"' . PHP_EOL;
    exit(1);
}

(static function (): void {
    if (file_exists($autoload = __DIR__ . '/vendor/autoload.php')) {
        include_once $autoload;
        return;
    }
    throw new RuntimeException('Unable to find the Composer autoloader.');
})();

try {
    $env_file = find_env();
} catch (EnvironmentNotFoundException $e) {
    Terminal::reset();
    Terminal::output()->writeln("<error>You need at least one environment file present to run a cosmic app. Please create them before continue.</error>");
    die(1);
}

SignalHandler::listen([Signal::interrupt, Signal::terminate], static function (Signal $signal, Info $info): void {
    Lifecycle::dispatchLifecycleEvent(Application::LIFECYCLE_APP_SIGNALED, ["signal" => $signal, "info" => $info]);
    Terminal::output()->writeln("\n\n 💔 <error>Interrupted by user.</error>");
    Terminal::restoreCursor();

    exit($signal->toInt());
});


$dotenv = is_phar() ?
    Dotenv\Dotenv::createMutable(Phar::running(), $env_file) :
    Dotenv\Dotenv::createMutable(getcwd(), $env_file);

$dotenv->safeLoad();

try {
    Terminal::loadThemes(__DIR__ . "/themes");
    Terminal::enableTheme(Env::get("APP_THEME", ThemeInterface::DEFAULT_THEME));

    $app = new Application(
        name: sprintf("%s %s", Terminal::getTheme()->getAppIcon(), Env::get("APP_NAME")),
        version: Env::appVersion()
    );

    $app->setAutoExit(false);
    $app->run();

} catch (Throwable $e) {
    throw new RuntimeException($e->getMessage(), $e->getCode(), $e);
}
