package shlex

// CompletionContext describes the completion state at the end of the input.
// It is the primary API for completion callers, replacing the manual
// tokens.CurrentPipeline().FilterRedirects().Words().currentToken() chains.
type CompletionContext struct {
	// Words are the dequoted word values in the current pipeline
	// (redirects filtered). When the cursor is inside a substitution
	// scope (e.g. $(...), these are the inner command's words.
	Words []string

	// CurrentWord is the word at the cursor position (dequoted Value).
	CurrentWord string

	// RawCurrentWord is the raw source of the current word (including quotes).
	// Use this to detect quotation state when QuotingState alone is insufficient.
	RawCurrentWord string

	// Prefix is the wordbreak prefix up to the cursor.
	Prefix string

	// QuotingState is the lexer state of the current word.
	// IN_WORD_STATE, QUOTING_STATE, QUOTING_ESCAPING_STATE, QUOTING_TRIPLE_STATE,
	// QUOTING_TRIPLE_ESCAPING_STATE, or ESCAPING_STATE.
	QuotingState LexerState

	// IsRedirect is true when the cursor is completing a redirect target
	// (e.g. after >, >>, <, etc.).
	IsRedirect bool

	// InLambdaParams is true when the cursor is inside a lambda parameter
	// list (e.g. after "{|" in elvish). The completion caller should
	// complete parameter names, not commands or arguments.
	InLambdaParams bool `json:",omitempty"`

	// Variable describes a variable reference ending the current word,
	// detected lexically on the lexer's final word. Nil when the word does
	// not end in a variable reference, or when the format does not
	// implement variableExpander.
	Variable *Variable `json:",omitempty"`

	// Span is the rune span of the current word in the input. Offsets
	// refer to the full input, also when the context describes the
	// innermost substitution's command.
	Span Span

	// Tokens is the raw token slice of the whole input — what Split
	// returns for the same line. Escape hatch for edge cases not covered
	// by the fields above.
	Tokens TokenSlice `json:"-"`

	// SubstitutionDepth is the number of unclosed substitution scopes
	// at the cursor position. 0 = cursor at top level. When > 0, the
	// derived fields (Words, CurrentWord, etc.) describe the innermost
	// substitution's command; Span and Tokens still refer to the full
	// input.
	SubstitutionDepth int `json:",omitempty"`

	format formatImpl
}

// Quote returns value quoted for insertion at the cursor position
// described by the context: an open quote is closed with the format's
// own escape rules and a bareword is quoted as a complete word, so the
// result can replace the whole raw current word. value is a full
// completion candidate matching the current word's typed prefix. Values meant to be
// inserted without a trailing space (nospace completions) may be passed
// as-is by the caller when quoting is not wanted.
func ( *CompletionContext) ( string) string {
	 := .format
	if  == nil {
		 = formatImpls[Default]
	}
	return quoteInsertion(, .QuotingState, )
}

// Complete parses s and returns a CompletionContext describing
// the completion state at the end of the string, using the given format.
//
// An empty or whitespace-terminated line yields an empty current word:
// the cursor starts a new word.
//
// When the cursor is inside an unclosed substitution scope (e.g. inside
// $(...), the context describes the innermost substitution's command,
// not the outer command.
func ( string,  Format) *CompletionContext {
	,  := formatImplFor()
	if ! {
		return &CompletionContext{QuotingState: START_STATE}
	}
	,  := Split(, )
	if  != nil || len() == 0 {
		return &CompletionContext{QuotingState: START_STATE}
	}

	// If cursor is inside an unclosed command substitution, build the
	// context from the inner tokens.
	if  := innermostUnclosedCommandScope();  >= 0 {
		 := buildCompletionContext([+1:], )
		.Tokens = 
		.SubstitutionDepth = countUnclosedCommandScopes()
		return 
	}

	 := buildCompletionContext(, )
	.Tokens = 
	return 
}

// buildCompletionContext derives the completion context fields from a
// token slice.
func buildCompletionContext( TokenSlice,  formatImpl) *CompletionContext {
	 := .CurrentPipeline()
	 := .FilterRedirects()
	 := .wordsWithSubstitutions()
	 := .Strings()

	 := &CompletionContext{
		Words:  ,
		format: ,
	}

	if len() >= 2 {
		 := [len()-2]
		if .WordbreakType.IsRedirect() {
			.IsRedirect = true
		}
	}

	var  *Token
	if .IsRedirect {
		 = &[len()-1]
	} else if len() > 0 {
		 = &[len()-1]
	}
	if  != nil {
		.CurrentWord = .Value
		.RawCurrentWord = .RawValue
		.QuotingState = .State
		.Span = .Span

		if ,  := .(variableExpander);  {
			if ,  := .Variable(*);  {
				.Variable = &
			}
		}
	}

	if .Variable != nil {
		.Variable.replacement = .RawCurrentWord
		if ,  := .(naiveWordSplitter);  {
			.Variable.replacement = .NaiveSplitWord(.RawCurrentWord)
		}
		.Variable.span = Span{
			Start: .Span.End - len([]rune(.Variable.replacement)),
			End:   .Span.End,
		}
	}

	.Prefix = .WordbreakPrefix()

	 := 0
	for ,  := range  {
		if .Type == WORDBREAK_TOKEN && .WordbreakType == WORDBREAK_LAMBDA_PIPE {
			++
		}
	}
	.InLambdaParams = %2 == 1

	return 
}