<?php

declare(strict_types=1);

use MintyPHP\App\AppContainer;
use MintyPHP\Http\RequestContext;

/**
 * Shared app bootstrap for non-module CLI commands.
 */
function cliBootstrapApp(string $channel = 'cli', string $path = 'bin/cli'): AppContainer
{
    static $booted = false;
    /** @var AppContainer|null $container */
    static $container = null;

    if (!$booted) {
        chdir(__DIR__ . '/..');
        require_once 'vendor/autoload.php';
        require_once 'config/config.php';
        require_once 'lib/Support/helpers.php';

        /** @var AppContainer $resolved */
        $resolved = require 'lib/App/registerContainer.php';
        setAppContainer($resolved);

        $container = $resolved;
        $booted = true;
    }

    RequestContext::start([
        'channel' => $channel,
        'method' => 'CLI',
        'path' => $path,
    ]);

    if (!$container instanceof AppContainer) {
        throw new RuntimeException('CLI app container bootstrap failed.');
    }

    return $container;
}
