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

/**
 * phpMyFAQ Console Application
 *
 * This Source Code Form is subject to the terms of the Mozilla Public License,
 * v. 2.0. If a copy of the MPL was not distributed with this file, You can
 * obtain one at https://mozilla.org/MPL/2.0/.
 *
 * @package   phpMyFAQ
 * @author    Thorsten Rinne <thorsten@phpmyfaq.de>
 * @copyright 2025-2026 phpMyFAQ Team
 * @license   https://www.mozilla.org/MPL/2.0/ Mozilla Public License Version 2.0
 * @link      https://www.phpmyfaq.de
 * @since     2025-06-25
 */

require __DIR__ . '/../phpmyfaq/src/Bootstrap.php';
require __DIR__ . '/../phpmyfaq/src/libs/autoload.php';

use phpMyFAQ\Bootstrap\ConfigDirectoryResolver;
use phpMyFAQ\Command\CreateHashesCommand;
use phpMyFAQ\Command\InstallCommand;
use phpMyFAQ\Command\McpServerCommand;
use phpMyFAQ\Command\SeedTestDataCommand;
use phpMyFAQ\Command\UpdateCommand;
use phpMyFAQ\Strings;
use phpMyFAQ\Translation;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\Console\Application;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\PhpFileLoader;

try {
    Translation::create()
        ->setTranslationsDir(PMF_LANGUAGE_DIR)
        ->setDefaultLanguage('en')
        ->setCurrentLanguage('en')
        ->setMultiByteLanguage();
} catch (Exception $exception) {
    echo $exception->getMessage();
}

// Initialize the multibyte string handler. In the web flow this is done by the
// LanguageListener; console commands have no such listener, so any command that
// touches Strings (e.g., Tags, Faq) would otherwise fail on a null handler.
Strings::init();

//
// Service Containers
//
$container = new ContainerBuilder();
$loader = new PhpFileLoader($container, new FileLocator(__DIR__));
try {
    $loader->load('../phpmyfaq/src/services.php');
} catch (Exception $e) {
    echo $e->getMessage();
}

// Detect whether phpMyFAQ is installed. Some commands depend on services that
// require a database connection (e.g., the MCP server resolves the Configuration
// singleton), so they can only be registered once an instance exists. The
// installer command itself must remain available before installation.
// Use the resolver so both the current and legacy config directories are honored.
$isInstalled = ConfigDirectoryResolver::resolveDatabaseFile() !== null;

$application = new Application();
$application->addCommand(new CreateHashesCommand($container->get('phpmyfaq.system'), $container->get('filesystem')));
$application->addCommand(new InstallCommand($container->get('phpmyfaq.system')));

if ($isInstalled) {
    $application->addCommand(new UpdateCommand());
    $application->addCommand(new McpServerCommand($container->get('phpmyfaq.service.mcp-server')));
    $application->addCommand(new SeedTestDataCommand());
}

$application->run();
