package uv

import (
	
	
	
	
	
	
	
	
	
	
	
	

	
	
	
)

// ErrReaderNotStarted is returned when the reader has not been started yet.
var ErrReaderNotStarted = fmt.Errorf("reader not started")

// DefaultEscTimeout is the default timeout at which the [TerminalReader] will
// process ESC sequences. It is set to 50 milliseconds.
const DefaultEscTimeout = 50 * time.Millisecond

// TerminalReader represents an input event loop that reads input events from
// a reader and parses them into human-readable events. It supports
// reading escape sequences, mouse events, and bracketed paste mode.
type TerminalReader struct {
	EventDecoder

	// MouseMode determines whether mouse events are enabled or not. This is a
	// platform-specific feature and is only available on Windows. When this is
	// true, the reader will be initialized to read mouse events using the
	// Windows Console API.
	MouseMode *MouseMode

	// EscTimeout is the escape character timeout duration. Most escape
	// sequences start with an escape character [ansi.ESC] and are followed by
	// one or more characters. If the next character is not received within
	// this timeout, the reader will assume that the escape sequence is
	// complete and will process the received characters as a complete escape
	// sequence.
	//
	// By default, this is set to [DefaultEscTimeout] (50 milliseconds).
	EscTimeout time.Duration

	r     io.Reader
	table map[string]Key // table is a lookup table for key sequences.

	term string // term is the terminal name $TERM.

	// paste is the bracketed paste mode buffer.
	// When nil, bracketed paste mode is disabled.
	paste []byte

	lookup bool // lookup indicates whether to use the lookup table for key sequences.

	// vtInput indicates whether we're using Windows Console API VT input mode.
	//nolint:unused,nolintlint
	vtInput bool

	eventScanner *eventScanner

	// We use these buffers to decode UTF-16 sequences and graphemes from the
	// Windows Console API and Win32-Input-Mode events.
	utf16Half   [2]bool    // 0 key up, 1 key down
	utf16Buf    [2][2]rune // 0 key up, 1 key down
	graphemeBuf [2][]rune  // 0 key up, 1 key down
	//nolint:unused,nolintlint
	lastMouseBtns uint32 // the last mouse button state for the previous event
	//nolint:unused,nolintlint
	lastWinsizeX, lastWinsizeY int16 // the last window size for the previous event to prevent multiple size events from firing

	logger Logger // The logger to use for debugging.
}

// NewTerminalReader returns a new input event reader. The reader streams input
// events from the terminal and parses escape sequences into human-readable
// events. It supports reading Terminfo databases.
//
// Use [TerminalReader.UseTerminfo] to use Terminfo defined key sequences.
// Use [TerminalReader.Legacy] to control legacy key encoding behavior.
//
// Example:
//
//	```go
//	var cr cancelreader.CancelReader
//	var evc chan Event
//	sc := NewTerminalReader(cr, os.Getenv("TERM"))
//	go sc.StreamEvents(ctx, evc)
//	```
func ( io.Reader,  string) *TerminalReader {
	 := &TerminalReader{
		EscTimeout: DefaultEscTimeout,
		r:          ,
		term:       ,
		lookup:     true, // Use lookup table by default.
	}
	.r = 
	if .table == nil {
		.table = buildKeysTable(.Legacy, .term, .UseTerminfo)
	}
	 := newEventScanner()
	.EventDecoder = .EventDecoder
	.table = .table
	.lookup = .lookup
	.setLogger(.logger)
	.eventScanner = 
	return 
}

// readBufSize is the size of the read buffer used to read input events at a time.
const readBufSize = 4096

// sendBytes reads data from the reader and sends it to the provided channel.
// It stops when an error occurs or when the context is closed.
func ( *TerminalReader) ( context.Context,  chan []byte) error {
	for {
		var  [readBufSize]byte
		,  := .r.Read([:])
		if  != nil {
			return  //nolint:wrapcheck
		}

		select {
		case <-.Done():
			return nil
		case  <- [:]:
		}
	}
}

// StreamEvents sends events to the provided channel. It stops when the context
// is closed or when an error occurs.
func ( *TerminalReader) ( context.Context,  chan<- Event) error {
	var  bytes.Buffer
	 := make(chan error, 1)
	 := make(chan []byte)
	 := time.NewTimer(.EscTimeout)
	 := time.Now().Add(.EscTimeout)

	var  sync.WaitGroup
	.Add(1)

	go func() {
		defer .Done()
		if  := .streamData(, );  != nil {
			if errors.Is(, io.EOF) || errors.Is(, cancelreader.ErrCanceled) {
				 <- nil
				return
			}
			 <- 
			return
		}
	}()

	for {
		select {
		case <-.Done():
			.sendEvents(, .Bytes(), true)
			.Wait()
			return nil
		case  := <-:
			.sendEvents(, .Bytes(), true)
			.Wait()
			return  // return the first error encountered
		case <-.C:
			.logf("timeout reached")

			// Timeout reached process the buffer including any incomplete sequences.
			var  int // n is the number of bytes processed
			 := time.Now().After()
			if .Len() > 0 &&  {
				.logf("timeout expired, processing buffer")
				 = .sendEvents(, .Bytes(), true)
			}

			if  > 0 {
				.Next()
			}

			if .Len() > 0 {
				if !.Stop() {
					// drain the channel if it was already running
					select {
					case <-.C:
					default:
					}
				}

				.logf("resetting timeout for remaining buffer")
				.Reset(.EscTimeout)
			}

		case  := <-:
			.logf("input: %q", )
			.Write()
			 = time.Now().Add(.EscTimeout)
			 := .sendEvents(, .Bytes(), false)
			if !.Stop() {
				// drain the channel if it was already running
				select {
				case <-.C:
				default:
				}
			}

			if  > 0 {
				.logf("processed %d bytes from buffer", )
				.Next()
			}

			if .Len() > 0 {
				.logf("resetting timeout for remaining buffer after parse")
				.Reset(.EscTimeout)
			}
		}
	}
}

// SetLogger sets the logger to use for debugging. If nil, no logging will be
// performed.
func ( *TerminalReader) ( Logger) {
	.logger = 
}

func ( *TerminalReader) ( chan<- Event,  []byte,  bool) int {
	,  := .eventScanner.scanEvents(, )
	for ,  := range  {
		 <- 
	}
	return 
}

// eventScanner scans the buffer for events and sends them to the event channel.
type eventScanner struct {
	EventDecoder

	utf16Half   [2]bool    // 0 key up, 1 key down
	utf16Buf    [2][2]rune // 0 key up, 1 key down
	graphemeBuf [2][]rune  // 0 key up, 1 key down
	paste       []byte
	table       map[string]Key
	lookup      bool
	logger      Logger
}

// newEventScanner creates a new event scanner.
func () *eventScanner {
	return &eventScanner{}
}

// setLogger sets the logger to use for debugging. If nil, no logging will be
// performed.
func ( *eventScanner) ( Logger) {
	.logger = 
}

func ( *eventScanner) ( string,  ...interface{}) {
	logf(.logger, , ...)
}

func ( *eventScanner) ( []byte,  bool) ( int,  []Event) {
	if len() == 0 {
		return 0, nil
	}

	var  int
	.logf("processing buf %d %q", len(), )
	,  = .deserializeWin32Input()
	 += 

	// Lookup table first
	if .lookup && len() > 2 && [0] == ansi.ESC {
		if ,  := .table[string()];  {
			return len(), []Event{KeyPressEvent()}
		}
	}

	// total is the total number of bytes processed
	for len() > 0 {
		 := [0] == ansi.ESC
		,  := .Decode()

		// Handle bracketed-paste
		if .paste != nil { //nolint:nestif
			if ,  := .(PasteEndEvent); ! {
				switch event := .(type) {
				case KeyPressEvent:
					if len(.Text) > 0 {
						.paste = append(.paste, .Text...)
					} else {
						 := string([:])
						 := strings.HasPrefix(, "\x1b[") && strings.HasSuffix(, "_")
						switch {
						case  && .Code == KeyEnter && .Code == .BaseCode:
							// This handles special cases where
							// win32-input-mode encodes newlines and other keys
							// as keypress events. We need to encode them as
							// their respective values.
							.paste = append(.paste, '\n')
						case  && unicode.IsControl(.Code) && .Code == .BaseCode:
							// This handles other cases such as tabs, escapes, etc.
							.paste = append(.paste, string(.Code)...)
						case !:
							// We ignore all other non-text win32-input-mode events.
							if  &&  <= 2 && ! {
								// If the event is an escape sequence and we
								// are not expired, we need to wait for more
								// input.
								return , 
							}
							.paste = append(.paste, ...)
						}
					}
				case UnknownEvent:
					if ! {
						// If the event is unknown and we are not expired, we
						// return need to try to decode the buffer again.
						return , 
					}
				default:
					// Everything else is ignored...
				}
				 = [:]
				 += 
				continue
			}
		}

		var  bool
		switch .(type) {
		case ignoredEvent:
			// ignore this event
			 = nil
		case UnknownEvent:
			 = true
			// Try to look up the event in the table.
			if ! {
				return , 
			}

			if ,  := .table[string([:])];  {
				 = append(, KeyPressEvent())
				return  + , 
			}

			 = append(, )
		case PasteStartEvent:
			.paste = []byte{} // reset the paste buffer
		case PasteEndEvent:
			var  []rune
			for len(.paste) > 0 {
				,  := utf8.DecodeRune(.paste)
				if  != utf8.RuneError {
					 = append(, )
				}
				.paste = .paste[:]
			}
			.paste = nil // reset the paste buffer
			 = append(, PasteEvent{string()})
		}

		if ! &&  != nil {
			if  &&  <= 2 && ! {
				// Wait for more input
				return , 
			}

			if ,  := .(MultiEvent);  {
				// If the event is a MultiEvent, append all events to the queue.
				 = append(, ...)
			} else {
				// Otherwise, just append the event to the queue.
				 = append(, )
			}
		}

		 = [:]
		 += 
	}

	return , 
}

func ( *eventScanner) () []byte {
	var  []byte
	for  := range .graphemeBuf {
		if len(.graphemeBuf[]) > 0 {
			switch  {
			case 1:
				 = append(, string(.graphemeBuf[])...)
			case 0:
				// Encode the release grapheme as Kitty Keyboard to get the release event.
				 := uniseg.NewGraphemes(string(.graphemeBuf[]))
				for .Next() {
					var  string
					 := .Str()
					for ,  := range  {
						if  == 0 {
							continue
						}
						if  > 0 {
							 += ":"
						}
						 += strconv.FormatInt(int64(), 10)
					}
					// This is dark :)
					// During serializing/deserializing of win32 input events, the
					// API will split a grapheme into runes and send them as a
					// keydown/keyup sequences. We collect the runes, decoded them
					// from UTF-16 just fine. However, [EventDecoder.Decode] will
					// always decode graphemes as [KeyPressEvent]s. Thus, to
					// workaround that and the existing API, while we are
					// intercepting win32 input events, we encode the grapheme
					// release events as Kitty Keyboard sequences so that
					// [EventDecoder.Decode] can properly decode them as
					// [KeyReleaseEvent]s.
					 := fmt.Sprintf("\x1b[%d;1:3;%su", .graphemeBuf[][0], )
					 = append(, ...)
				}
			}
			.graphemeBuf[] = .graphemeBuf[][:0] // reset the buffer
		}
	}
	return 
}

func ( *eventScanner) ( int,  rune) {
	if .utf16Half[] {
		// We have a half pair that needs to be decoded.
		.utf16Half[] = false
		.utf16Buf[][1] = 
		 := utf16.DecodeRune(.utf16Buf[][0], .utf16Buf[][1])
		.graphemeBuf[] = append(.graphemeBuf[], )
	} else if utf16.IsSurrogate() {
		// This is the first half of a UTF-16 surrogate pair.
		.utf16Half[] = true
		.utf16Buf[][0] = 
	} else {
		// This should be a single UTF-16 that can be converted
		// to UTF-8.
		.graphemeBuf[] = append(.graphemeBuf[], )
	}
}

// deserializeWin32Input deserializes the Win32 input events converting
// KeyEventRecrods to bytes. Before returning the bytes, it will also try to
// decode any UTF-16 pairs that might be present in the input buffer.
func ( *eventScanner) ( []byte) (int, []byte) {
	 := ansi.GetParser()
	defer ansi.PutParser()

	var  int
	var  byte
	 := make([]byte, 0, len())

	for len() > 0 {
		, , ,  := ansi.DecodeSequence(, , )
		switch  {
		case 0:
			if .Command() == '_' { // Win32 Input Mode
				,  := .Param(0, 0)
				if  == 0 {
					// This is either a serialized KeyEventRecord or a UTF-16
					// pair.
					,  := .Param(2, 0)
					,  := .Param(3, 0)
					 = clamp(, 0, 1) // kd is the key down state (0 or 1)
					.storeGraphemeRune(, rune())
					 += 
					break
				}
			}
			fallthrough
		default:
			 = append(, .encodeGraphemeBufs()...)
			 = append(, ...)
		}

		 = 
		 = [:]
	}

	 = append(, .encodeGraphemeBufs()...)

	return , 
}

func ( *TerminalReader) ( string,  ...interface{}) {
	logf(.logger, , ...)
}

func ( Logger,  string,  ...interface{}) {
	if  == nil {
		return
	}
	.Printf(, ...)
}