package shlex

import 

// nushellFormat implements Format for nushell lexing.
// Key differences from bash:
//   - Backtick (`) is a quote character (not an escape like PowerShell)
//   - Backslash outside quotes is a regular word character (not an escape)
//   - $'...' and $"..." are interpolated strings ($ prefix + standard quote)
//   - C-style escapes in double quotes with a richer set than bash:
//     \" \' \\ \/ \b \f \r \n \t \0 \a \e \( \) \{ \} \$ \^ \# \| \~
//     \xHH and \u{X...} are deferred (see format-nushell.md → Deferred Features)
//   - No POSIX list operators (no &&, ||, &)
//   - No input redirection (< is a comparison operator, not a redirect)
//   - Stream redirect operators: out>, err>, out+err>, err+out>, o>, e>,
//     o+e>, e+o> and pipe variants: err>|, e>|, o+e>|, e+o>|,
//     out+err>|, err+out>|
//     (out>| and o>| are plain pipes — stdout to pipe = normal piping)
//   - r#'...'# raw strings need multi-rune opener support (deferred — see
//     format-nushell.md → Deferred Features)
type nushellFormat struct{}

func (nushellFormat) () tokenClassifier {
	 := tokenClassifier{}
	.addRuneClass(spaceRunes, spaceRuneClass)
	.addRuneClass(escapingQuoteRunes, escapingQuoteRuneClass)       // "
	.addRuneClass(nonEscapingQuoteRunes, nonEscapingQuoteRuneClass) // '
	// Nushell: backtick is a quote character (not an escape)
	.addRuneClass("`", nonEscapingQuoteRuneClass)
	.addRuneClass(escapeRunes, escapeRuneClass)
	.addRuneClass(commentRunes, commentRuneClass)

	// Nushell operators: |, ;, >, >>
	// No &&, ||, & — no POSIX list operators
	// No < — nushell does not support input redirection;
	//   < is only a comparison operator or type-parameter delimiter (in signatures)
	// ( and ) are subexpression delimiters
	.addWordbreaks("|;>()")
	return 
}

func (nushellFormat) ( string) WordbreakType {
	switch  {
	case "|":
		return WORDBREAK_PIPE
	case ";":
		return WORDBREAK_LIST_SEQUENTIAL
	case ">":
		return WORDBREAK_REDIRECT_OUTPUT
	case ">>":
		return WORDBREAK_REDIRECT_OUTPUT_APPEND
	default:
		return WORDBREAK_UNKNOWN
	}
}

func (nushellFormat) () map[string]WordbreakType { return nil }

func (nushellFormat) () bool           { return false }
func (nushellFormat) () bool  { return false }
func (nushellFormat) () bool                 { return false }
func (nushellFormat) () bool          { return false }
func (nushellFormat) () map[rune]bool { return nil }
func (nushellFormat) ( string) string               { return nushellQuoteWord() }
func (nushellFormat) () bool                { return false }
func (nushellFormat) () bool                  { return false }

// EscapingQuoteUnescape implements the escapingQuoteUnescaper interface.
// Nushell double-quoted strings support C-style escapes with a richer set
// than bash. Recognized escapes produce the corresponding character(s);
// unrecognized escapes keep both the backslash and the rune literally
// (nushell itself errors on unrecognized escapes, but for completion being
// lenient is better than failing).
func (nushellFormat) ( rune) (string, bool) {
	switch  {
	case '"':
		return "\"", true
	case '\'':
		return "'", true
	case '\\':
		return "\\", true
	case '/':
		return "/", true
	case 'b':
		return "\b", true
	case 'f':
		return "\f", true
	case 'r':
		return "\r", true
	case 'n':
		return "\n", true
	case 't':
		return "\t", true
	case '0':
		return "\x00", true
	case 'a':
		return "\a", true
	case 'e':
		return "\x1b", true
	case '(':
		return "(", true
	case ')':
		return ")", true
	case '{':
		return "{", true
	case '}':
		return "}", true
	case '$':
		return "$", true
	case '^':
		return "^", true
	case '#':
		return "#", true
	case '|':
		return "|", true
	case '~':
		return "~", true
	default:
		return "", false
	}
}

// nushellStreamRedirects maps the word portion of stream-redirect operators
// (the part before >) to their WordbreakType. The PostProcess step merges
// these with a following > or >| wordbreak token.
var nushellStreamRedirects = map[string]WordbreakType{
	"out":     WORDBREAK_REDIRECT_OUTPUT,
	"err":     WORDBREAK_REDIRECT_OUTPUT,
	"o":       WORDBREAK_REDIRECT_OUTPUT,
	"e":       WORDBREAK_REDIRECT_OUTPUT,
	"out+err": WORDBREAK_REDIRECT_OUTPUT_BOTH,
	"err+out": WORDBREAK_REDIRECT_OUTPUT_BOTH,
	"o+e":     WORDBREAK_REDIRECT_OUTPUT_BOTH,
	"e+o":     WORDBREAK_REDIRECT_OUTPUT_BOTH,
}

// PostProcess merges nushell stream-redirect operators. The tokenizer
// produces e.g. `out` as a WORD_TOKEN and `>` (or `>>`, `>|`) as a
// WORDBREAK_TOKEN because the rune-classifier only handles single-rune
// word breaks. This step detects adjacent word+wordbreak sequences like
// `out>`, `err>`, `o+e>`, `e>|`, `o+e>|` and reclassifies them as single
// WORDBREAK_TOKENs with the appropriate WordbreakType.
//
// The tokenizer emits `>` and `|` as separate WORDBREAK_TOKENs (since `>|`
// is not a recognized operator in ClassifyOperator), so pipe variants like
// `err>|` appear as three tokens: WORD `err`, WORDBREAK `>`, WORDBREAK `|`.
// This step merges all three into one.
func (nushellFormat) ( TokenSlice) TokenSlice {
	 := make(TokenSlice, 0, len())
	for  := 0;  < len(); ++ {
		 := []

		// Look for bare WORD_TOKEN immediately followed by WORDBREAK_TOKEN starting with '>'
		// Only merge bare words (Value == RawValue) — quoted words like 'out' or "out"
		// are string literals, not stream redirect operators.
		if .Type == WORD_TOKEN && .Value == .RawValue && +1 < len() {
			 := [+1]
			if .Type == WORDBREAK_TOKEN && .adjoins() && len(.RawValue) > 0 && .RawValue[0] == '>' {
				if ,  := nushellStreamRedirects[.Value];  {
					 := 
					 := strings.HasPrefix(.RawValue, ">>")

					// Check for an adjacent `|` token after the `>` (pipe variant).
					// The tokenizer emits `>` and `|` as separate tokens.
					 := -1
					if +2 < len() {
						 := [+2]
						if .Type == WORDBREAK_TOKEN && .adjoins() && .RawValue == "|" {
							 =  + 2
						}
					}

					if  >= 0 {
						// out>| is a plain pipe in nushell (stdout to pipe = normal piping).
						// err>| and o+e>| (and their err+out/e+o aliases) pipe stderr/both.
						if  == WORDBREAK_REDIRECT_OUTPUT && .Value != "err" && .Value != "e" {
							 = WORDBREAK_PIPE
						} else {
							 = WORDBREAK_PIPE_WITH_STDERR
						}
					} else if  {
						if  == WORDBREAK_REDIRECT_OUTPUT_BOTH {
							 = WORDBREAK_REDIRECT_OUTPUT_BOTH_APPEND
						} else {
							 = WORDBREAK_REDIRECT_OUTPUT_APPEND
						}
					}

					 :=  + 1
					if  >= 0 {
						 = 
					}

					 := Token{
						Type:          WORDBREAK_TOKEN,
						Value:         .Value + [+1].Value,
						RawValue:      .RawValue + [+1].RawValue,
						Span:          Span{Start: .Span.Start, End: [].Span.End},
						State:         [].State,
						WordbreakType: ,
					}

					if  >= 0 {
						.Value += [].Value
						.RawValue += [].RawValue
					}

					 = append(, )
					 = 
					continue
				}
			}
		}

		 = append(, )
	}

	// Reclassify ( and ) as substitution delimiters
	for  := range  {
		 := &[]
		if .Type == WORDBREAK_TOKEN && .Value == "(" {
			.WordbreakType = WORDBREAK_SUBSTITUTION_OPEN
		}
		if .Type == WORDBREAK_TOKEN && .Value == ")" {
			.WordbreakType = WORDBREAK_SUBSTITUTION_CLOSE
		}
	}
	return 
}

// Variable implements variableExpander. Nushell expands `$name` in
// barewords only — quotes are literal strings, not interpolations — and
// there is no `${` form. Variable names may contain hyphens.
func (nushellFormat) ( Token) (Variable, bool) {
	return variableRef(, variableRules{
		expands:         func( LexerState) bool { return  == IN_WORD_STATE },
		barewordEscapes: true,
		nameStart:       isNushellNameStart,
		nameRune:        isNushellNameRune,
	})
}

func isNushellNameStart( rune) bool {
	return isPosixNameStart()
}

func isNushellNameRune( rune) bool {
	switch {
	case isPosixNameRune(),  == '-':
		return true
	default:
		return false
	}
}

func (nushellFormat) ( string) bool {
	return bareWordRe.MatchString()
}