#!/bin/bash

cliInitialize()
{
    cliUpdateCommands;

    # Many commands shell out via `sudo -u "$docker_install_user"` (backup
    # engines, permission fixes, file copies). Resolve it up front so commands
    # run from the WebUI — e.g. `setup finalize`, `backup` — get a valid user
    # instead of an empty one. The app category still runs the fuller
    # checkInstallTypeRequirement below.
    resolveDockerInstallUser;

    # Dynamic routing - auto-discover ALL categories!
    local category="$initial_command1"
    
    # Handle empty command as help
    if [[ -z "$category" ]]; then
        category="help"
    fi
    
    local commands_file="$install_scripts_dir/cli/commands/$category/cli_${category}_commands.sh"
    local header_file="$install_scripts_dir/cli/commands/$category/cli_${category}_header.sh"
    
    # Check if both header and commands files exist
    if [[ -f "$commands_file" && -f "$header_file" ]]; then
        # Special handling for app category
        if [[ "$category" == "app" ]]; then
            checkInstallTypeRequirement;
        fi
        
        # Source the commands file
        source "$commands_file"
        
        # Call the handler function
        "cliHandle${category^}Commands"
    else
        isNotice "Unknown command: ${RED}$category${NC}"
        
        # Show help if command not found
        local help_commands_file="$install_scripts_dir/cli/commands/help/cli_help_commands.sh"
        if [[ -f "$help_commands_file" ]]; then
            source "$help_commands_file"
            handleHelpCommands
        fi
    fi
}
