package ansi

import (
	

	
	
)

// State represents the state of the ANSI escape sequence parser used by
// [DecodeSequence].
type State = byte

// ANSI escape sequence states used by [DecodeSequence].
const (
	NormalState State = iota
	PrefixState
	ParamsState
	IntermedState
	EscapeState
	StringState
)

// DecodeSequence decodes the first ANSI escape sequence or a printable
// grapheme from the given data. It returns the sequence slice, the number of
// bytes read, the cell width for each sequence, and the new state.
//
// The cell width will always be 0 for control and escape sequences, 1 for
// ASCII printable characters, and the number of cells other Unicode characters
// occupy. It uses the uniseg package to calculate the width of Unicode
// graphemes and characters. This means it will always do grapheme clustering
// (mode 2027).
//
// Passing a non-nil [*Parser] as the last argument will allow the decoder to
// collect sequence parameters, data, and commands. The parser cmd will have
// the packed command value that contains intermediate and prefix characters.
// In the case of a OSC sequence, the cmd will be the OSC command number. Use
// [Cmd] and [Param] types to unpack command intermediates and prefixes as well
// as parameters.
//
// Zero [Cmd] means the CSI, DCS, or ESC sequence is invalid. Moreover, checking the
// validity of other data sequences, OSC, DCS, etc, will require checking for
// the returned sequence terminator bytes such as ST (ESC \\) and BEL).
//
// We store the command byte in [Cmd] in the most significant byte, the
// prefix byte in the next byte, and the intermediate byte in the least
// significant byte. This is done to avoid using a struct to store the command
// and its intermediates and prefixes. The command byte is always the least
// significant byte i.e. [Cmd & 0xff]. Use the [Cmd] type to unpack the
// command, intermediate, and prefix bytes. Note that we only collect the last
// prefix character and intermediate byte.
//
// The [p.Params] slice will contain the parameters of the sequence. Any
// sub-parameter will have the [parser.HasMoreFlag] set. Use the [Param] type
// to unpack the parameters.
//
// Example:
//
//	var state byte // the initial state is always zero [NormalState]
//	p := NewParser(32, 1024) // create a new parser with a 32 params buffer and 1024 data buffer (optional)
//	input := []byte("\x1b[31mHello, World!\x1b[0m")
//	for len(input) > 0 {
//		seq, width, n, newState := DecodeSequence(input, state, p)
//		log.Printf("seq: %q, width: %d", seq, width)
//		state = newState
//		input = input[n:]
//	}
//
// This function treats the text as a sequence of grapheme clusters.
func [ string | []byte]( ,  byte,  *Parser) ( ,  int,  int,  byte) {
	return decodeSequence(GraphemeWidth, , , )
}

// DecodeSequenceWc decodes the first ANSI escape sequence or a printable
// grapheme from the given data. It returns the sequence slice, the number of
// bytes read, the cell width for each sequence, and the new state.
//
// The cell width will always be 0 for control and escape sequences, 1 for
// ASCII printable characters, and the number of cells other Unicode characters
// occupy. It uses the uniseg package to calculate the width of Unicode
// graphemes and characters. This means it will always do grapheme clustering
// (mode 2027).
//
// Passing a non-nil [*Parser] as the last argument will allow the decoder to
// collect sequence parameters, data, and commands. The parser cmd will have
// the packed command value that contains intermediate and prefix characters.
// In the case of a OSC sequence, the cmd will be the OSC command number. Use
// [Cmd] and [Param] types to unpack command intermediates and prefixes as well
// as parameters.
//
// Zero [Cmd] means the CSI, DCS, or ESC sequence is invalid. Moreover, checking the
// validity of other data sequences, OSC, DCS, etc, will require checking for
// the returned sequence terminator bytes such as ST (ESC \\) and BEL).
//
// We store the command byte in [Cmd] in the most significant byte, the
// prefix byte in the next byte, and the intermediate byte in the least
// significant byte. This is done to avoid using a struct to store the command
// and its intermediates and prefixes. The command byte is always the least
// significant byte i.e. [Cmd & 0xff]. Use the [Cmd] type to unpack the
// command, intermediate, and prefix bytes. Note that we only collect the last
// prefix character and intermediate byte.
//
// The [p.Params] slice will contain the parameters of the sequence. Any
// sub-parameter will have the [parser.HasMoreFlag] set. Use the [Param] type
// to unpack the parameters.
//
// Example:
//
//	var state byte // the initial state is always zero [NormalState]
//	p := NewParser(32, 1024) // create a new parser with a 32 params buffer and 1024 data buffer (optional)
//	input := []byte("\x1b[31mHello, World!\x1b[0m")
//	for len(input) > 0 {
//		seq, width, n, newState := DecodeSequenceWc(input, state, p)
//		log.Printf("seq: %q, width: %d", seq, width)
//		state = newState
//		input = input[n:]
//	}
//
// This function treats the text as a sequence of wide characters and runes.
func [ string | []byte]( ,  byte,  *Parser) ( ,  int,  int,  byte) {
	return decodeSequence(WcWidth, , , )
}

func [ string | []byte]( Method,  ,  State,  *Parser) ( ,  int,  int,  byte) {
	for  := 0;  < len(); ++ {
		 := []

		switch  {
		case NormalState:
			switch  {
			case ESC:
				if  != nil {
					if len(.params) > 0 {
						.params[0] = parser.MissingParam
					}
					.cmd = 0
					.paramsLen = 0
					.dataLen = 0
				}
				 = EscapeState
				continue
			case CSI, DCS:
				if  != nil {
					if len(.params) > 0 {
						.params[0] = parser.MissingParam
					}
					.cmd = 0
					.paramsLen = 0
					.dataLen = 0
				}
				 = PrefixState
				continue
			case OSC, APC, SOS, PM:
				if  != nil {
					.cmd = parser.MissingCommand
					.dataLen = 0
				}
				 = StringState
				continue
			}

			if  != nil {
				.dataLen = 0
				.paramsLen = 0
				.cmd = 0
			}
			if  > US &&  < DEL {
				// ASCII printable characters
				return [ : +1], 1, 1, NormalState
			}

			if  <= US ||  == DEL ||  < 0xC0 {
				// C0 & C1 control characters & DEL
				return [ : +1], 0, 1, NormalState
			}

			if utf8.RuneStart() {
				,  = FirstGraphemeCluster(, )
				 += len()
				return [:], , , NormalState
			}

			// Invalid UTF-8 sequence
			return [:], 0, , NormalState
		case PrefixState:
			if  >= '<' &&  <= '?' {
				if  != nil {
					// We only collect the last prefix character.
					.cmd &^= 0xff << parser.PrefixShift
					.cmd |= int() << parser.PrefixShift
				}
				break
			}

			 = ParamsState
			fallthrough
		case ParamsState:
			if  >= '0' &&  <= '9' {
				if  != nil {
					if .params[.paramsLen] == parser.MissingParam {
						.params[.paramsLen] = 0
					}

					.params[.paramsLen] *= 10
					.params[.paramsLen] += int( - '0')
				}
				break
			}

			if  == ':' {
				if  != nil {
					.params[.paramsLen] |= parser.HasMoreFlag
				}
			}

			if  == ';' ||  == ':' {
				if  != nil {
					.paramsLen++
					if .paramsLen < len(.params) {
						.params[.paramsLen] = parser.MissingParam
					}
				}
				break
			}

			 = IntermedState
			fallthrough
		case IntermedState:
			if  >= ' ' &&  <= '/' {
				if  != nil {
					.cmd &^= 0xff << parser.IntermedShift
					.cmd |= int() << parser.IntermedShift
				}
				break
			}

			if  != nil {
				// Increment the last parameter
				if .paramsLen > 0 && .paramsLen < len(.params)-1 ||
					.paramsLen == 0 && len(.params) > 0 && .params[0] != parser.MissingParam {
					.paramsLen++
				}
			}

			if  >= '@' &&  <= '~' {
				if  != nil {
					.cmd &^= 0xff
					.cmd |= int()
				}

				if HasDcsPrefix() {
					// Continue to collect DCS data
					if  != nil {
						.dataLen = 0
					}
					 = StringState
					continue
				}

				return [:+1], 0,  + 1, NormalState
			}

			// Invalid CSI/DCS sequence
			return [:], 0, , NormalState
		case EscapeState:
			switch  {
			case '[', 'P':
				if  != nil {
					if len(.params) > 0 {
						.params[0] = parser.MissingParam
					}
					.paramsLen = 0
					.cmd = 0
				}
				 = PrefixState
				continue
			case ']', 'X', '^', '_':
				if  != nil {
					.cmd = parser.MissingCommand
					.dataLen = 0
				}
				 = StringState
				continue
			}

			if  >= ' ' &&  <= '/' {
				if  != nil {
					.cmd &^= 0xff << parser.IntermedShift
					.cmd |= int() << parser.IntermedShift
				}
				continue
			} else if  >= '0' &&  <= '~' {
				if  != nil {
					.cmd &^= 0xff
					.cmd |= int()
				}
				return [:+1], 0,  + 1, NormalState
			}

			// Invalid escape sequence
			return [:], 0, , NormalState
		case StringState:
			switch  {
			case BEL:
				if HasOscPrefix() {
					parseOscCmd()
					return [:+1], 0,  + 1, NormalState
				}
			case CAN, SUB:
				if HasOscPrefix() {
					// Ensure we parse the OSC command number
					parseOscCmd()
				}

				// Cancel the sequence
				return [:], 0, , NormalState
			case ST:
				if HasOscPrefix() {
					// Ensure we parse the OSC command number
					parseOscCmd()
				}

				return [:+1], 0,  + 1, NormalState
			case ESC:
				if HasStPrefix([:]) {
					if HasOscPrefix() {
						// Ensure we parse the OSC command number
						parseOscCmd()
					}

					// End of string 7-bit (ST)
					return [:+2], 0,  + 2, NormalState
				}

				// Otherwise, cancel the sequence
				return [:], 0, , NormalState
			}

			if  != nil && .dataLen < len(.data) {
				.data[.dataLen] = 
				.dataLen++

				// Parse the OSC command number
				if  == ';' && HasOscPrefix() {
					parseOscCmd()
				}
			}
		}
	}

	return , 0, len(), 
}

func ( *Parser) {
	if  == nil || .cmd != parser.MissingCommand {
		return
	}
	for  := range .dataLen {
		 := .data[]
		if  < '0' ||  > '9' {
			break
		}
		if .cmd == parser.MissingCommand {
			.cmd = 0
		}
		.cmd *= 10
		.cmd += int( - '0')
	}
}

// Equal returns true if the given byte slices are equal.
func [ string | []byte](,  ) bool {
	return string() == string()
}

// HasPrefix returns true if the given byte slice has prefix.
func [ string | []byte](,  ) bool {
	return len() >= len() && Equal([0:len()], )
}

// HasSuffix returns true if the given byte slice has suffix.
func [ string | []byte](,  ) bool {
	return len() >= len() && Equal([len()-len():], )
}

// HasCsiPrefix returns true if the given byte slice has a CSI prefix.
func [ string | []byte]( ) bool {
	return (len() > 0 && [0] == CSI) ||
		(len() > 1 && [0] == ESC && [1] == '[')
}

// HasOscPrefix returns true if the given byte slice has an OSC prefix.
func [ string | []byte]( ) bool {
	return (len() > 0 && [0] == OSC) ||
		(len() > 1 && [0] == ESC && [1] == ']')
}

// HasApcPrefix returns true if the given byte slice has an APC prefix.
func [ string | []byte]( ) bool {
	return (len() > 0 && [0] == APC) ||
		(len() > 1 && [0] == ESC && [1] == '_')
}

// HasDcsPrefix returns true if the given byte slice has a DCS prefix.
func [ string | []byte]( ) bool {
	return (len() > 0 && [0] == DCS) ||
		(len() > 1 && [0] == ESC && [1] == 'P')
}

// HasSosPrefix returns true if the given byte slice has a SOS prefix.
func [ string | []byte]( ) bool {
	return (len() > 0 && [0] == SOS) ||
		(len() > 1 && [0] == ESC && [1] == 'X')
}

// HasPmPrefix returns true if the given byte slice has a PM prefix.
func [ string | []byte]( ) bool {
	return (len() > 0 && [0] == PM) ||
		(len() > 1 && [0] == ESC && [1] == '^')
}

// HasStPrefix returns true if the given byte slice has a ST prefix.
func [ string | []byte]( ) bool {
	return (len() > 0 && [0] == ST) ||
		(len() > 1 && [0] == ESC && [1] == '\\')
}

// HasEscPrefix returns true if the given byte slice has an ESC prefix.
func [ string | []byte]( ) bool {
	return len() > 0 && [0] == ESC
}

// FirstGraphemeCluster returns the first grapheme cluster in the given string
// or byte slice, and its monospace display width.
func [ string | []byte]( ,  Method) (, int) {
	switch b := any().(type) {
	case string:
		 := graphemes.FromString().First()
		if  == WcWidth {
			return (), wcClusterWidth()
		}
		return (), dwOptions.String()
	case []byte:
		 := graphemes.FromBytes().First()
		if  == WcWidth {
			return (), wcClusterWidth()
		}
		return (), dwOptions.Bytes()
	}
	panic("unreachable")
}

// Cmd represents a sequence command. This is used to pack/unpack a sequence
// command with its intermediate and prefix characters. Those are commonly
// found in CSI and DCS sequences.
type Cmd int

// Prefix returns the unpacked prefix byte of the CSI sequence.
// This is always gonna be one of the following '<' '=' '>' '?' and in the
// range of 0x3C-0x3F.
// Zero is returned if the sequence does not have a prefix.
func ( Cmd) () byte {
	return byte(parser.Prefix(int())) //nolint:gosec
}

// Intermediate returns the unpacked intermediate byte of the CSI sequence.
// An intermediate byte is in the range of 0x20-0x2F. This includes these
// characters from ' ', '!', '"', '#', '$', '%', '&', ”', '(', ')', '*', '+',
// ',', '-', '.', '/'.
// Zero is returned if the sequence does not have an intermediate byte.
func ( Cmd) () byte {
	return byte(parser.Intermediate(int())) //nolint:gosec
}

// Final returns the unpacked command byte of the CSI sequence.
func ( Cmd) () byte {
	return byte(parser.Command(int())) //nolint:gosec
}

// Command packs a command with the given prefix, intermediate, and final. A
// zero byte means the sequence does not have a prefix or intermediate.
//
// Prefixes are in the range of 0x3C-0x3F that is one of `<=>?`.
//
// Intermediates are in the range of 0x20-0x2F that is anything in
// `!"#$%&'()*+,-./`.
//
// Final bytes are in the range of 0x40-0x7E that is anything in the range
// `@A–Z[\]^_`a–z{|}~`.
func (, ,  byte) ( int) {
	 = int()
	 |= int() << parser.PrefixShift
	 |= int() << parser.IntermedShift
	return 
}

// Param represents a sequence parameter. Sequence parameters with
// sub-parameters are packed with the HasMoreFlag set. This is used to unpack
// the parameters from a CSI and DCS sequences.
type Param int

// Param returns the unpacked parameter at the given index.
// It returns the default value if the parameter is missing.
func ( Param) ( int) int {
	 := int() & parser.ParamMask
	if  == parser.MissingParam {
		return 
	}
	return 
}

// HasMore unpacks the HasMoreFlag from the parameter.
func ( Param) () bool {
	return &parser.HasMoreFlag != 0
}

// Parameter packs an escape code parameter with the given parameter and
// whether this parameter has following sub-parameters.
func ( int,  bool) ( int) {
	 =  & parser.ParamMask
	if  {
		 |= parser.HasMoreFlag
	}
	return 
}