package lipgloss

import (
	
	
	
	
	

	uv 
	
)

// queryBackgroundColor queries the terminal for the background color.
// If the terminal does not support querying the background color, nil is
// returned.
//
// Note: you will need to set the input to raw mode before calling this
// function.
//
//	state, _ := term.MakeRaw(in.Fd())
//	defer term.Restore(in.Fd(), state)
//
// copied from x/term@v0.1.3.
func ( io.Reader,  io.Writer) ( color.Color,  error) {
	 = queryTerminal(, , defaultQueryTimeout,
		func( string,  *ansi.Parser) bool {
			switch {
			case ansi.HasOscPrefix():
				switch .Command() {
				case 11: // OSC 11
					 := strings.Split(string(.Data()), ";")
					if len() != 2 {
						break // invalid, but we still need to parse the next sequence
					}
					 = ansi.XParseColor([1])
				}
			case ansi.HasCsiPrefix():
				switch .Command() {
				case ansi.Command('?', 0, 'c'): // DA1
					return false
				}
			}
			return true
		}, ansi.RequestBackgroundColor+ansi.RequestPrimaryDeviceAttributes)
	return
}

const defaultQueryTimeout = time.Second * 2

// queryTerminalFilter is a function that filters input events using a type
// switch. If false is returned, the QueryTerminal function will stop reading
// input.
type queryTerminalFilter func(seq string, pa *ansi.Parser) bool

// queryTerminal queries the terminal for support of various features and
// returns a list of response events.
// Most of the time, you will need to set stdin to raw mode before calling this
// function.
// Note: This function will block until the terminal responds or the timeout
// is reached.
// copied from x/term@v0.1.3.
func (
	 io.Reader,
	 io.Writer,
	 time.Duration,
	 queryTerminalFilter,
	 string,
) error {
	// We use [uv.NewCancelReader] because it uses a different Windows
	// implementation than the on in the [cancelreader] library, which uses
	// the Cancel IO API to cancel reads instead of using Overlapped IO.
	,  := uv.NewCancelReader()
	if  != nil {
		return fmt.Errorf("could not create cancel reader: %w", )
	}

	defer .Close() //nolint: errcheck

	 := make(chan struct{}, 1)
	defer close()
	go func() {
		select {
		case <-:
		case <-time.After():
			.Cancel()
		}
	}()

	if ,  := io.WriteString(, );  != nil {
		return fmt.Errorf("could not write query: %w", )
	}

	 := ansi.GetParser()
	defer ansi.PutParser()

	var  []byte    // Accumulate partial responses before filtering
	var  [256]byte // 256 bytes should be enough for most responses
	var  byte
	for {
		,  := .Read([:])
		if  != nil {
			return fmt.Errorf("could not read from input: %w", )
		}

		 := [:]
		for  > 0 {
			, , ,  := ansi.DecodeSequence([:], , )
			 = append(, ...)

			if  == ansi.NormalState {
				if !(string(), ) {
					return nil
				}

				 = [:0]
			}

			 = 
			 -= 
			 = [:]
		}
	}
}