# lt completion for Bash shell
# Auto-generated by lt CLI - supports arbitrary nesting depth

<%
// Helper to generate safe variable name from path
function varName(path) {
  return path.replace(/-/g, '_') + '_cmds';
}

// Recursively collect all nodes that have children
function collectNodesWithChildren(nodes, result = []) {
  for (const node of nodes) {
    if (node.children.length > 0) {
      result.push(node);
      collectNodesWithChildren(node.children, result);
    }
  }
  return result;
}

// Get command names from children
function getCommandNames(children) {
  return children.map(c => c.name).join(' ');
}

const nodesWithChildren = collectNodesWithChildren(props.commandTree);
-%>
_lt_completions() {
    local cur prev words cword
    _init_completion || return

    # Root level commands
    local root_cmds="<%- getCommandNames(props.commandTree) %>"

<% for (const node of nodesWithChildren) { -%>
    # <%- node.path %> subcommands
    local <%- varName(node.path) %>="<%- getCommandNames(node.children) %>"

<% } -%>
    case "${cword}" in
        1)
            COMPREPLY=( $(compgen -W "${root_cmds}" -- "${cur}") )
            ;;
<% for (let depth = 2; depth <= props.maxDepth; depth++) { -%>
        <%- depth %>)
<%
  // Generate nested case statements for this depth
  function generateBashCases(nodes, currentDepth, targetDepth, wordIndex) {
    let output = '';
    const indent = '            ' + '    '.repeat(currentDepth - 2);

    if (currentDepth === targetDepth) {
      // We're at the target depth, provide completions
      for (const node of nodes) {
        if (node.children.length > 0) {
          output += `${indent}${node.name})\n`;
          output += `${indent}    COMPREPLY=( $(compgen -W "\${${varName(node.path)}}" -- "\${cur}") )\n`;
          output += `${indent}    ;;\n`;
        }
      }
    } else {
      // Need to go deeper with nested case
      for (const node of nodes) {
        if (node.children.length > 0) {
          const hasGrandchildren = node.children.some(c => c.children.length > 0);
          if (hasGrandchildren || currentDepth + 1 === targetDepth) {
            output += `${indent}${node.name})\n`;
            output += `${indent}    case "\${words[${currentDepth}]}" in\n`;
            output += generateBashCases(node.children, currentDepth + 1, targetDepth, wordIndex);
            output += `${indent}    esac\n`;
            output += `${indent}    ;;\n`;
          }
        }
      }
    }
    return output;
  }
-%>
            case "${words[1]}" in
<%- generateBashCases(props.commandTree, 2, depth, 1) -%>
            esac
            ;;
<% } -%>
        *)
            # Complete common flags
            local flags="--help --version --noConfirm --dry-run"
            COMPREPLY=( $(compgen -W "${flags}" -- "${cur}") )
            ;;
    esac
}

complete -F _lt_completions lt
