package shlex

import (
	
	
)

// powershellFormat implements Format for PowerShell lexing.
// Key differences from bash:
//   - Backtick (`) is the escape character, not backslash (\)
//   - ” inside single quotes → literal ' (doubled quote)
//   - "" inside double quotes → literal " (doubled quote)
//   - No single-quote-as-quote for outer quote pairs in the POSIX sense;
//     both ' and " are quote chars
//   - Backtick + newline is line continuation (consumed, not part of word)
//   - Block comments <# ... #> (multi-line)
//   - --% stop-parsing token (raw mode for remainder of line)
//   - Stream redirects: 2>, 2>>, 2>&1, 1>&2, *>, *>> (merged in PostProcess)
//   - Here-strings (@'...'@, @"..."@) are deferred
type powershellFormat struct{}

func (powershellFormat) () tokenClassifier {
	 := tokenClassifier{}
	.addRuneClass(spaceRunes, spaceRuneClass)
	.addRuneClass(escapingQuoteRunes, escapingQuoteRuneClass)       // " is escaping quote
	.addRuneClass(nonEscapingQuoteRunes, nonEscapingQuoteRuneClass) // ' is non-escaping
	// PowerShell: backtick is the escape character, not backslash
	.addRuneClass("`", escapeRuneClass)
	.addRuneClass(commentRunes, commentRuneClass)

	// PowerShell operators: |, ;, >, >>, &&, ||, &
	// Note: & is the call operator, not a background operator
	// ( and ) are subexpression/substitution delimiters
	.addWordbreaks("|;&><()")
	return 
}

func (powershellFormat) ( string) WordbreakType {
	switch  {
	case "|":
		return WORDBREAK_PIPE
	case ";":
		return WORDBREAK_LIST_SEQUENTIAL
	case ">", ">>":
		return WORDBREAK_REDIRECT_OUTPUT
	case "<":
		return WORDBREAK_REDIRECT_INPUT
	case "&&":
		return WORDBREAK_LIST_AND
	case "||":
		return WORDBREAK_LIST_OR
	case "&":
		return WORDBREAK_UNKNOWN // call operator, not a list operator
	default:
		return WORDBREAK_UNKNOWN
	}
}

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

func (powershellFormat) () bool           { return true } // '' → '
func (powershellFormat) () bool  { return false }
func (powershellFormat) () bool                 { return true }
func (powershellFormat) () bool          { return false }
func (powershellFormat) () map[rune]bool { return nil }
func (powershellFormat) ( string) string               { return powershellQuoteWord() }
func (powershellFormat) () bool                { return false }
func (powershellFormat) () bool                  { return false }

// IsLineContinuation implements lineContinuationEscaper. PowerShell's
// backtick followed by \n or \r is a line continuation — the sequence is
// consumed and the word continues on the next line.
func (powershellFormat) ( rune) bool {
	return  == '\n' ||  == '\r'
}

// BlockCommentOpener implements blockCommenter. PowerShell supports
// multi-line block comments delimited by <# and #>.
func (powershellFormat) () string { return "<#" }

// BlockCommentCloser implements blockCommenter.
func (powershellFormat) () string { return "#>" }

// StopParsingWord implements stopParsingToken. PowerShell's --% token
// stops PowerShell from interpreting subsequent input.
func (powershellFormat) () string { return "--%" }

// PostProcess merges PowerShell stream-redirect operators. The tokenizer
// produces e.g. `2` as a WORD_TOKEN and `>` (or `>>`) as a WORDBREAK_TOKEN.
// This step detects adjacent word+wordbreak sequences like `2>`, `2>>`,
// `2>&1`, `1>&2`, `*>`, `*>>` and reclassifies them as single
// WORDBREAK_TOKENs with the appropriate WordbreakType.
func (powershellFormat) ( TokenSlice) TokenSlice {
	 := make(TokenSlice, 0, len())
	for  := 0;  < len(); ++ {
		 := []

		// Look for bare WORD_TOKEN (digit or *) immediately followed by
		// WORDBREAK_TOKEN starting with '>' (redirect operator)
		if .Type == WORD_TOKEN && .Value == .RawValue && +1 < len() {
			 := [+1]
			if .Type == WORDBREAK_TOKEN && .adjoins() &&
				.WordbreakType.IsRedirect() && len(.RawValue) > 0 && .RawValue[0] == '>' {
				// Check if the word is a valid stream number or *
				if .Value == "*" || (len(.Value) == 1 && .Value[0] >= '1' && .Value[0] <= '6') {
					// Check for merging redirect: next token after > is &N
					// e.g. 2>&1 — the & and digit are separate wordbreak/word tokens
					 := .WordbreakType
					 := .RawValue + .RawValue
					 := .Value + .Value
					 := Span{Start: .Span.Start, End: .Span.End}

					// Check for &N pattern (stream merge) in the token after next
					if +2 < len() && [+2].Type == WORDBREAK_TOKEN &&
						[+2].Value == "&" && [+2].adjoins() {
						if +3 < len() && [+3].Type == WORD_TOKEN &&
							[+3].Value == [+3].RawValue &&
							[+3].adjoins([+2]) &&
							len([+3].Value) == 1 &&
							([+3].Value[0] == '1' || [+3].Value[0] == '2') {
							// 2>&1 pattern — merge all four tokens
							 += [+2].RawValue + [+3].RawValue
							 += [+2].Value + [+3].Value
							.End = [+3].Span.End
							 = WORDBREAK_REDIRECT_OUTPUT_BOTH
							 := Token{
								Type:          WORDBREAK_TOKEN,
								Value:         ,
								RawValue:      ,
								Span:          ,
								State:         [+3].State,
								WordbreakType: ,
							}
							 = append(, )
							 += 3
							continue
						}
					}

					 := Token{
						Type:          WORDBREAK_TOKEN,
						Value:         ,
						RawValue:      ,
						Span:          ,
						State:         .State,
						WordbreakType: ,
					}
					 = append(, )
					 += 1
					continue
				}
			}
		}

		 = append(, )
	}

	// Second pass: merge $ + ( into substitution opener and reclassify ) as closer
	 := make(TokenSlice, 0, len())
	for  := 0;  < len(); ++ {
		 := []
		// Detect $ + ( adjacency → merge into WORDBREAK_SUBSTITUTION_OPEN
		if .Type == WORD_TOKEN && .Value == "$" && +1 < len() {
			 := [+1]
			if .Type == WORDBREAK_TOKEN && .Value == "(" && .adjoins() {
				 := Token{
					Type:          WORDBREAK_TOKEN,
					Value:         "$(",
					RawValue:      .RawValue + .RawValue,
					Span:          Span{Start: .Span.Start, End: .Span.End},
					State:         .State,
					WordbreakType: WORDBREAK_SUBSTITUTION_OPEN,
				}
				 = append(, )
				++
				continue
			}
		}
		// Reclassify standalone ( as substitution opener
		if .Type == WORDBREAK_TOKEN && .Value == "(" {
			.WordbreakType = WORDBREAK_SUBSTITUTION_OPEN
		}
		// Reclassify ) as substitution closer
		if .Type == WORDBREAK_TOKEN && .Value == ")" {
			.WordbreakType = WORDBREAK_SUBSTITUTION_CLOSE
		}
		 = append(, )
	}
	return 
}

// powershellNumericWordRe matches digit-leading words that PowerShell
// evaluates to a different value standalone (e.g. 0x1f -> 31, 2e3 -> 2000,
// 2kb -> 2048, 2l -> 2, 2us -> 2, trailing 2. -> 2). Words rendering as
// their own value (42, 2.5) are not matched.
var powershellNumericWordRe = regexp.MustCompile(
	`^0[xX][0-9a-fA-F_]+$` +
		`|^0[bB][01_]+$` +
		`|[0-9][0-9_]*(\.[0-9_]*)?[eE][0-9]+$` +
		`|^[0-9][0-9_]*\.$` +
		`|(?i)^[0-9][0-9_]*(\.[0-9_]*)?(l|u|ul|d|kb|mb|gb|tb|pb|us)$`,
)

func (powershellFormat) ( string) bool {
	// digit-leading words with operator runes are arithmetic in
	// PowerShell command position (2+2 computes 4), so they are not inert
	if  != "" && [0] >= '0' && [0] <= '9' && strings.ContainsAny(, "+-*/%") {
		return false
	}
	return !powershellNumericWordRe.MatchString() && bareWordRe.MatchString()
}