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

/**
 * This file is part of Galette (https://galette.eu).
 * SPDX-FileCopyrightText: Copyright © 2003-2026 The Galette Team
 * SPDX-License-Identifier: GPL-3.0-or-later
 */

declare(strict_types=1);

use function Safe\define;

//relative to this script, not to the current directory, which may be
//anything from a cron job or a script - or another Galette checkout.
//The application directory is GALETTE_DIR when set, else the "galette"
//directory next to bin/, else the only one of its siblings holding Galette
//(it may have been renamed); dependencies are not loaded yet, hence no Safe
$basepath ??= (static function (): string {
    $marker = 'includes/galette.inc.php';
    $fail = static function (string $message): never {
        fwrite(STDERR, $message . PHP_EOL); //@phpstan-ignore theCodingMachineSafe.function
        exit(1);
    };

    $dir = getenv('GALETTE_DIR');
    if ($dir !== false && $dir !== '') {
        $real = realpath($dir); //@phpstan-ignore theCodingMachineSafe.function
        if ($real === false || !is_file($real . '/' . $marker)) {
            $fail(sprintf('GALETTE_DIR is set to "%s", which is not a Galette directory.', $dir));
        }
        return $real . '/';
    }

    $root = \dirname(__DIR__);
    if (is_file($root . '/galette/' . $marker)) {
        return $root . '/galette/';
    }

    $found = glob($root . '/*/' . $marker) ?: []; //@phpstan-ignore theCodingMachineSafe.function
    if (count($found) === 1) {
        return \dirname($found[0], 2) . '/';
    }
    $fail(
        (
            count($found) === 0
                ? sprintf('No Galette directory found next to "%s".', __DIR__)
                : sprintf(
                    'Several Galette directories found next to "%s": %s.',
                    __DIR__,
                    implode(', ', array_map(static fn(string $file): string => \dirname($file, 2), $found)),
                )
        ) . ' Set the GALETTE_DIR environment variable to the one to use.'
    );
})();

\define('GALETTE_ENV', 'CLI'); //@phpstan-ignore theCodingMachineSafe.function (dependencies not loaded yet)
if (getenv('GALETTE_TESTS')) {
    require_once __DIR__ . '/../tests/test_env.inc.php';
}
//test environment already defines it
if (!\defined('GALETTE_ROOT')) {
    \define('GALETTE_ROOT', \realpath($basepath) . '/'); //@phpstan-ignore theCodingMachineSafe.function, theCodingMachineSafe.function (dependencies not loaded yet)
}

//specific logfile for console, read back by includes/galette.inc.php through the
//scope of the require below, hence unused as far as the sniff can tell
$logfile = 'galette_cli'; // phpcs:ignore SlevomatCodingStandard.Variables.UnusedVariable.UnusedVariable

require_once $basepath . 'vendor/autoload.php';
require_once $basepath . 'includes/sys_config/versions.inc.php';

// Compiling locales only works on files; boot without database, like the installer.
// Options may come before the command name, look for it rather than at argv[1]
$installer = in_array(
    (new \Symfony\Component\Console\Input\ArgvInput())->getFirstArgument(),
    ['galette:install', 'galette:compile-locales'],
    strict: true
);

// In test mode, GALETTE_CONFIG_PATH is already set to the test config directory,
// so skip the production config file check to allow all commands to be registered.
if (!getenv('GALETTE_TESTS') && ($installer || !file_exists($basepath . 'config/config.inc.php'))) {
    define('GALETTE_INSTALLER', value: true);
    $installer = true; //consider we're installing
} elseif ($installer) {
    define('GALETTE_INSTALLER', value: true);
}
require_once $basepath . 'includes/galette.inc.php';

//no session on CLI: nothing would carry its id from one run to the next, and
//starting one fails whenever the configured handler (redis, a sessions directory
//the cron user cannot write...) is not available to the CLI
$_SESSION = [];

/** @var \Galette\Core\Plugins $plugins */
$gapp = new \Galette\Core\SlimApp($plugins);
$app = $gapp->getApp();
$container = $app->getContainer();

$console = new \Galette\Console\GaletteApplication($basepath);
$console->init(
    $container,
    $app,
    $container->get(\Slim\Routing\RouteCollector::class)
);
$console->run();
