package shlex

// innermostUnclosedCommandScope returns the TokenSlice index of the opener
// of the innermost unclosed command substitution scope, or -1 if the cursor
// is at top level. Arithmetic ($((...))) and backtick scopes are not
// command scopes — they don't produce an inner completion context.
func innermostUnclosedCommandScope( TokenSlice) int {
	 := 0
	var  []int

	for ,  := range  {
		switch .WordbreakType {
		case WORDBREAK_SUBSTITUTION_OPEN:
			if isArithmeticOpener() {
				continue
			}
			++
			 = append(, )
		case WORDBREAK_SUBSTITUTION_CLOSE:
			if isArithmeticCloser() {
				continue
			}
			if  > 0 {
				--
				 = [:len()-1]
			}
		}
	}

	if  > 0 && len() > 0 {
		return [len()-1]
	}
	return -1
}

func isArithmeticOpener( Token) bool {
	return len(.RawValue) >= 2 && .RawValue[len(.RawValue)-2] == '('
}

func isArithmeticCloser( Token) bool {
	return len(.RawValue) >= 2 && .RawValue[0] == ')' && .RawValue[1] == ')'
}

// countUnclosedCommandScopes returns the number of unclosed command
// substitution scopes in the token slice. Arithmetic scopes are excluded.
func countUnclosedCommandScopes( TokenSlice) int {
	 := 0
	for ,  := range  {
		switch .WordbreakType {
		case WORDBREAK_SUBSTITUTION_OPEN:
			if isArithmeticOpener() {
				continue
			}
			++
		case WORDBREAK_SUBSTITUTION_CLOSE:
			if isArithmeticCloser() {
				continue
			}
			if  > 0 {
				--
			}
		}
	}
	return 
}