package uv

import (
	
	
	
	

	
	
)

// DefaultBufferSize is the default size of the input buffer used for reading
// terminal events.
const DefaultBufferSize = 4096

// DefaultEventTimeout is the default duration to wait for input events before
// timing out.
const DefaultEventTimeout = 100 * time.Millisecond

// Options represents options for creating a new [Terminal].
type Options struct {
	// BufferSize is the size of the input buffer used for reading terminal
	// events. If zero, [DefaultBufferSize] is used.
	BufferSize int

	// EventTimeout is the duration to wait for input events before timing out.
	// If zero, a default of 100 milliseconds is used.
	EventTimeout time.Duration

	// LegacyKeyEncoding represents any legacy key encoding ambiguities. By
	// default, the terminal will use its preferred key encoding settings.
	LegacyKeyEncoding LegacyKeyEncoding

	// LookupKeys whether to use a lookup table for common key sequences. If
	// true, the terminal will use a lookup table to quickly identify common
	// key sequences, reducing the need for more complex decoding logic. This
	// can improve performance for common key sequences at the cost of
	// increased memory usage.
	//
	// This is enabled by default.
	LookupKeys bool

	// UseTerminfoKeys whether to use terminfo databases key definitions to
	// build up the keys lookup table. If true, the terminal will use terminfo
	// databases key definitions to build up the keys lookup table, which can
	// provide more accurate key mappings for legacy non-xterm like terminals.
	//
	// This won't take effect if [TerminalOptions.LookupKeys] is false, since
	// the lookup table won't be used.
	//
	// This is disabled by default.
	UseTerminfoKeys bool

	// Logger is an optional logger for tracing terminal I/O operations.
	// If nil, no logging is performed.
	Logger Logger
}

// DefaultOptions returns the default [Terminal] options.
func () *Options {
	return &Options{
		BufferSize:   DefaultBufferSize,
		EventTimeout: DefaultEventTimeout,
		LookupKeys:   true,
	}
}

// Terminal represents an interactive terminal application.
type Terminal struct {
	con   Console
	opts  *Options
	scr   *TerminalScreen
	pr    pollReader
	buf   []byte
	evc   chan Event
	errg  errgroup.Group
	winch chan os.Signal
	donec chan struct{}
}

// DefaultTerminal creates a new [Terminal] instance using the default standard
// console and the given options. Options can be nil to use the default
// options.
//
// This is a convenience function for creating a terminal that uses the
// standard input and output file descriptors.
func () *Terminal {
	return NewTerminal(nil, nil)
}

// ControllingTerminal creates a new [Terminal] instance using the controlling
// terminal's input and output file descriptors.
// Options can be nil to use the default options.
//
// This is a convenience function for creating a terminal that uses the
// controlling TTY of the current process.
func () (*Terminal, error) {
	,  := ControllingConsole()
	if  != nil {
		return nil, 
	}
	return NewTerminal(, nil), nil
}

// NewTerminal creates a new [Terminal] instance with the given console and
// options.
// Options can be nil to use the default options.
func ( Console,  *Options) *Terminal {
	 := &Terminal{}
	if  == nil {
		 = DefaultConsole()
	}
	if  == nil {
		 = DefaultOptions()
	}
	if .BufferSize <= 0 {
		.BufferSize = DefaultBufferSize
	}
	if .EventTimeout <= 0 {
		.EventTimeout = DefaultEventTimeout
	}
	.con = 
	.opts = 
	.scr = NewTerminalScreen(.con.Writer(), .con.Environ())
	.buf = make([]byte, .BufferSize)
	// These channels never close during the terminal's lifetime.
	.evc = make(chan Event)
	.winch = make(chan os.Signal, 1) // buffered to avoid missing signals
	if .Logger != nil {
		.scr.rend.SetLogger(.Logger)
	}
	return 
}

// GetSize returns the current size of the terminal in characters and pixels.
func ( *Terminal) () (,  int,  error) {
	, ,  := .con.GetSize()
	if  != nil {
		return 0, 0, fmt.Errorf("getting terminal size: %w", )
	}
	return int(), int(), nil
}

// GetWinsize returns the current size of the terminal as a [Winsize] struct.
// This includes both character dimensions (columns and rows) and pixel
// dimensions (xpixel and ypixel).
//
// Note that this only returns the pixel dimensions on Unix-like systems that
// support the TIOCGWINSZ ioctl. On other platforms, the pixel dimensions may
// be zero or not available.
func ( *Terminal) () (*Winsize, error) {
	,  := .con.GetWinsize()
	if  != nil {
		return nil, fmt.Errorf("getting terminal winsize: %w", )
	}
	return , nil
}

// Screen returns the terminal's screen.
func ( *Terminal) () *TerminalScreen {
	return .scr
}

// Events returns the terminal's event channel.
func ( *Terminal) () <-chan Event {
	return .evc
}

// Start starts the terminal application event loop. This is a non-blocking
// call. Use [Terminal.Wait] to wait for the terminal to exit.
func ( *Terminal) () error {
	,  := .con.MakeRaw()
	if  != nil {
		return fmt.Errorf("failed to set terminal to raw mode: %w", )
	}

	 := newEventScanner()
	.lookup = .opts.LookupKeys
	if .lookup {
		.table = buildKeysTable(.opts.LegacyKeyEncoding, .con.Getenv("TERM"), .opts.UseTerminfoKeys)
	}
	if .opts.Logger != nil {
		.setLogger(.opts.Logger)
	}
	 := make(chan []byte)
	.donec = make(chan struct{})
	.pr,  = newPollReader(.con.Reader())
	if  != nil {
		return fmt.Errorf("failed to create poll reader: %w", )
	}

	// input loop
	.errg.Go(func() error {
		for {
			,  := .pr.Read(.buf)
			if  != nil {
				return fmt.Errorf("reading terminal input: %w", )
			}
			select {
			case  <- .buf[:]:
			case <-.donec:
				return nil
			}
		}
	})

	// event loop
	 := func( []byte,  bool) int {
		,  := .scanEvents(, )
		for ,  := range  {
			.handleEvent()
			.SendEvent()
		}
		return 
	}
	.errg.Go(func() error {
		var  []byte
		 := time.NewTimer(.opts.EventTimeout)
		 := time.Now().Add(.opts.EventTimeout)

		for {
			select {
			case <-.donec:
				return nil
			case <-.C:
				 := len() > 0 && time.Now().After()
				 := (, )
				if  > 0 {
					 = [min(, len()):]
				}
				if len() > 0 {
					.Reset(.opts.EventTimeout)
				}
			case  := <-:
				 = append(, ...)
				 := (, false)
				 = time.Now().Add(.opts.EventTimeout)
				.Stop()
				if  > 0 {
					 = [min(, len()):]
				}
				if len() > 0 {
					.Reset(.opts.EventTimeout)
				}
			}
		}
	})

	 := func() error {
		,  := .con.GetWinsize()
		if  != nil {
			return fmt.Errorf("getting terminal size: %w", )
		}
		if .Col > 0 && .Row > 0 {
			.SendEvent(WindowSizeEvent{
				Width:  int(.Col),
				Height: int(.Row),
			})
		}
		if .Xpixel > 0 && .Ypixel > 0 {
			.SendEvent(PixelSizeEvent{
				Width:  int(.Xpixel),
				Height: int(.Ypixel),
			})
		}
		return nil
	}

	// winch handler
	NotifyWinch(.winch)
	.errg.Go(func() error {
		for {
			select {
			case <-.donec:
				return nil
			case <-.winch:
				if  := ();  != nil {
					return 
				}
			}
		}
	})

	// init window size
	.errg.Go(func() error {
		if  := ();  != nil {
			return 
		}
		return nil
	})

	// Restore any previous screen state.
	.scr.Restore()
	// Query whether the terminal supports Unicode core mode (DEC mode 2027) so
	// we can negotiate grapheme-cluster width. The response is handled in the
	// event loop.
	.scr.requestGraphemeWidth()
	if  := .scr.Flush();  != nil {
		return fmt.Errorf("failed to flush terminal screen: %w", )
	}

	return nil
}

// handleEvent reacts to internal events before they are forwarded to the
// application. It negotiates Unicode core mode (DEC mode 2027): when the
// terminal reports the mode is in a settable or active state, it enables
// grapheme-cluster width so wide-glyph measurement matches the terminal. The
// event is still forwarded to the application.
//
// The mode is only enabled for settable/active states (mode set, reset but
// settable, or permanently set). It is explicitly not enabled when the mode is
// not recognized or permanently reset, since those terminals cannot honor it.
// Enabling goes through the screen's locked write path so it cannot race with
// the application's Render/Flush.
func ( *Terminal) ( Event) {
	if ,  := .(ModeReportEvent);  {
		if .Mode == ansi.ModeUnicodeCore &&
			(.Value.IsSet() || .Value == ansi.ModeReset) {
			.scr.enableGraphemeWidth()
		}
	}
}

// Wait waits for the terminal event loop to exit and returns any error that
// occurred.
func ( *Terminal) () error {
	if  := .errg.Wait();  != nil {
		return fmt.Errorf("terminal event loop error: %w", )
	}
	return nil
}

// Stop stops the terminal event loop. It is safe to call Stop without a
// prior [Terminal.Start], and safe to call Stop multiple times in a row.
// After Stop returns, [Terminal.Start] may be called again to resume.
func ( *Terminal) () error {
	if .donec != nil {
		select {
		case <-.donec:
			// Already closed.
		default:
			close(.donec)
		}
	}
	if .winch != nil {
		signal.Stop(.winch)
	}
	if .pr != nil {
		.pr.Cancel()
		_ = .pr.Close()
		.pr = nil
	}
	.scr.Reset()
	if  := .scr.Flush();  != nil {
		_ = .con.Restore()
		return fmt.Errorf("failed to flush terminal screen: %w", )
	}
	if  := .con.Restore();  != nil {
		return fmt.Errorf("failed to restore terminal state: %w", )
	}
	return nil
}

// SendEvent sends an event to the terminal's event channel.
//
// This can be used to inject custom events into the terminal's event loop,
// such as timer events, signals, or application-specific events.
func ( *Terminal) ( Event) {
	select {
	case .evc <- :
	case <-.donec:
	}
}

// Write writes data directly to the terminal's console output.
//
// This is a low-level operation that bypasses the terminal screen buffering
// and writes directly to the console output handler, usually [os.Stdout] or
// the controlling TTY.
func ( *Terminal) ( []byte) ( int,  error) {
	return .con.Write()
}

// Read reads data from the terminal's console input.
//
// This is a low-level operation that bypasses the terminal event processing
// and reads directly from the console input handler, usually [os.Stdin] or the
// controlling TTY. Use this method with caution, as it may interfere with the
// terminal's event loop and screen management.
func ( *Terminal) ( []byte) ( int,  error) {
	return .con.Read()
}