<?php
namespace boru\ai\Cli;

use boru\ai\AI;
use boru\ai\Bootstrap;
use boru\ai\Config\Config;
use boru\ai\Config\ConfigLoader;
use boru\cli2\CLI;
use boru\cli2\CLIContext;
use boru\cli2\Commands\HelpCommand;
use boru\cli2\Params\Option;
use RuntimeException;

class AICli
{
    private static $isInit = false;
    protected static $cli;

    public function __construct()
    {
        static::init();
    }

    public static function init($force = false)
    {
        if (self::$isInit && !$force) {
            return static::$cli;
        }
        self::$isInit = true;
        $cli = CLI::create('ai|boru/ai CLI utilities');
        $cli->params(array(
            Option::create('*c|config|Path to config.php or config.json'),
        ));

        $cli->onHandle(function (CLIContext $ctx) {
            $configPath = $ctx->get('config');
            if (!file_exists($configPath)) {
                throw new RuntimeException('Config file not found: ' . $configPath);
            }

            $extension = strtolower(pathinfo($configPath, PATHINFO_EXTENSION));
            if ($extension === 'json') {
                $config = ConfigLoader::fromJsonFile($configPath);
            } else {
                $loaded = require $configPath;
                if ($loaded instanceof Config) {
                    $config = $loaded;
                } elseif (is_array($loaded)) {
                    $config = new Config($loaded);
                } else {
                    throw new RuntimeException('Config PHP file must return a Config instance or array: ' . $configPath);
                }
            }

            if (!$config instanceof Config) {
                throw new RuntimeException('Config loader did not return a Config instance');
            }

            AI::config($config);
            Bootstrap::registerDefaults($config);
            $ctx->set('config', $config);
        });

        static::$cli = $cli;

        static::registerCommands();

        return static::$cli;
    }

    private static function registerCommands()
    {
        static::$cli->register(new HelpCommand());
        static::$cli->register(new ChatCommand());
        static::$cli->register(new ConversationShowCommand());
        static::$cli->register(new PersistencePruneCommand());
        static::$cli->register(new ToolCallsListCommand());
    }
}
