package lipgloss

import (
	
	
	
	

	
)

func ( term.File,  term.File) (color.Color, error) {
	,  := term.MakeRaw(.Fd())
	if  != nil {
		return nil, fmt.Errorf("error setting raw state to detect background color: %w", )
	}

	defer term.Restore(.Fd(), ) //nolint:errcheck

	,  := queryBackgroundColor(, )
	if  != nil {
		return nil, 
	}

	return , nil
}

// BackgroundColor queries the terminal's background color. Typically, you'll
// want to query against stdin and either stdout or stderr, depending on what
// you're writing to.
//
// This function is intended for standalone Lip Gloss use only. If you're using
// Bubble Tea, listen for tea.BackgroundColorMsg in your update function.
func ( term.File,  term.File) ( color.Color,  error) {
	if runtime.GOOS == "windows" { //nolint:nestif
		// On Windows, when the input/output is redirected or piped, we need to
		// open the console explicitly.
		// See https://learn.microsoft.com/en-us/windows/console/getstdhandle#remarks
		if !term.IsTerminal(.Fd()) {
			,  := os.OpenFile("CONIN$", os.O_RDWR, 0o644) //nolint:gosec
			if  != nil {
				return nil, fmt.Errorf("error opening CONIN$: %w", )
			}
			 = 
		}
		if !term.IsTerminal(.Fd()) {
			,  := os.OpenFile("CONOUT$", os.O_RDWR, 0o644) //nolint:gosec
			if  != nil {
				return nil, fmt.Errorf("error opening CONOUT$: %w", )
			}
			 = 
		}
		return backgroundColor(, )
	}

	// NOTE: On Unix, one of the given files must be a tty.
	if !term.IsTerminal(.Fd()) || !term.IsTerminal(.Fd()) {
		return nil, fmt.Errorf("input/output is not a terminal")
	}
	for ,  := range []term.File{, } {
		if ,  = backgroundColor(, );  == nil {
			return , nil
		}
	}

	return , 
}

// HasDarkBackground detects whether the terminal has a light or dark
// background.
//
// Typically, you'll want to query against stdin and either stdout or stderr
// depending on what you're writing to.
//
//	hasDarkBG := HasDarkBackground(os.Stdin, os.Stdout)
//	lightDark := LightDark(hasDarkBG)
//	myHotColor := lightDark("#ff0000", "#0000ff")
//
// This is intended for use in standalone Lip Gloss only. In Bubble Tea, listen
// for tea.BackgroundColorMsg in your Update function.
//
//	case tea.BackgroundColorMsg:
//	    hasDarkBackground = msg.IsDark()
//
// By default, this function will return true if it encounters an error.
func ( term.File,  term.File) bool {
	,  := BackgroundColor(, )
	if  != nil ||  == nil {
		return true
	}
	return isDarkColor()
}