//go:build !windows

package tcelllivepage

import (
	
	
	
	
	
	
	
	
	
	
	
	

	
	
	
	lp 
)

// vt10x glyph attribute bits (unexported in vt10x).
const (
	vtAttrReverse   = 1 << 0
	vtAttrUnderline = 1 << 1
	vtAttrBold      = 1 << 2
	vtAttrItalic    = 1 << 4
)

// RunCmd serves cmd over HTTP using livepage. The command runs on a Unix PTY,
// so programs see a real terminal; its output is mirrored into a [Screen]. It
// blocks until the command exits or ctx is canceled.
func ( context.Context,  *exec.Cmd,  CmdOpts) error {
	// TODO migrate to github.com/aymanbagabas/go-pty for win support, also slog, return HTTP handler
	if .Printf == nil {
		.Printf = func(string, ...any) {}
	}
	if .Env == nil {
		.Env = append(os.Environ(), "TERM=xterm-256color")
	} else {
		.Env = append(.Env, "TERM=xterm-256color")
	}

	,  := context.WithCancel()
	defer ()

	,  := NewScreen(, Opts{
		Title:           .Title,
		RefreshInterval: 50 * time.Millisecond,
		Live: lp.Opts{
			Debounce: 50 * time.Millisecond,
		},
	})
	if  != nil {
		return fmt.Errorf("livepage screen: %w", )
	}
	.Sync()

	,  := net.Listen("tcp", .Addr)
	if  != nil {
		.Fini()
		return fmt.Errorf("livepage listen: %w", )
	}

	 := &http.Server{
		Handler:           .Handler(),
		ReadHeaderTimeout: 5 * time.Second,
	}
	go func() {
		if  := .Serve();  != nil &&
			!errors.Is(, http.ErrServerClosed) {

			.Printf("livepage: %s", )
		}
	}()
	.Printf("Livepage: http://%s/", displayAddr(.Addr()))

	,  := .Size()
	if  <= 0 {
		 = DefaultCols
	}
	if  <= 0 {
		 = DefaultRows
	}

	,  := pty.StartWithSize(, &pty.Winsize{
		Rows: uint16(),
		Cols: uint16(),
	})
	if  != nil {
		_ = .Close()
		.Fini()
		return fmt.Errorf("livepage pty: %w", )
	}

	 := &livepageBridge{
		screen: ,
		term:   vt10x.New(vt10x.WithSize(, )),
		ptmx:   ,
	}

	var  sync.WaitGroup
	.Add(3)
	go func() {
		defer .Done()
		.readLoop()
	}()
	go func() {
		defer .Done()
		.renderLoop()
	}()
	go func() {
		defer .Done()
		.inputLoop()
	}()

	// wait for the child to exit or for a signal
	 := make(chan struct{})
	var  error
	go func() {
		 = .Wait()
		close()
	}()

	 := false
	select {
	case <-.Done():
		 = true
		_ = .Process.Signal(syscall.SIGTERM)
		select {
		case <-:
		case <-time.After(2 * time.Second):
			_ = .Process.Kill()
			<-
		}
	case <-:
	}

	()
	,  := context.WithTimeout(
		context.Background(), 3*time.Second)
	defer ()
	_ = .Shutdown()
	_ = .Close()
	.Fini()
	.Wait()

	if  {
		return nil
	}
	if  != nil && !errors.Is(, os.ErrProcessDone) {
		return fmt.Errorf("livepage cmd exited: %w\n\ncmd: %s\n\noutput:\n%s",
			, .String(), .output())
	}

	return nil
}

// livepageBridge mirrors a PTY-backed terminal into a livepage screen.
type livepageBridge struct {
	screen *Screen
	term   vt10x.Terminal
	ptmx   *os.File

	// out holds the last [maxOut] bytes of the child's output, for errors.
	out []byte

	termMu  sync.Mutex
	writeMu sync.Mutex
	dirty   atomic.Bool
}

// maxOut is the number of child output bytes kept for error reporting.
const maxOut = 4096

// output returns the tail of the child's output. Read it only after the read
// loop has finished.
func ( *livepageBridge) () string {
	return string(.out)
}

// readLoop feeds the child's output into the virtual terminal.
func ( *livepageBridge) () {
	 := make([]byte, 32*1024)
	for {
		,  := .ptmx.Read()
		if  > 0 {
			 := [:]

			.out = append(.out, ...)
			if len(.out) > maxOut {
				.out = .out[len(.out)-maxOut:]
			}

			.termMu.Lock()
			_, _ = .term.Write()
			var  string
			if bytes.Contains(, []byte("\x1b[6n")) {
				 := .term.Cursor()
				 = fmt.Sprintf("\x1b[%d;%dR", .Y+1, .X+1)
			}
			.termMu.Unlock()

			if  != "" {
				.writePTY([]byte())
			}
			.dirty.Store(true)
		}
		if  != nil {
			return
		}
	}
}

// renderLoop copies the virtual terminal grid into the livepage screen.
func ( *livepageBridge) ( context.Context) {
	 := time.NewTicker(50 * time.Millisecond)
	defer .Stop()

	.render()
	for {
		select {
		case <-.Done():
			return
		case <-.C:
			if !.dirty.Swap(false) {
				continue
			}
			.render()
		}
	}
}

func ( *livepageBridge) () {
	.termMu.Lock()
	,  := renderTerminal(.term, .screen)
	.termMu.Unlock()

	if  {
		.screen.ShowCursor(.X, .Y)
	} else {
		.screen.HideCursor()
	}
	// Sync (not Show) keeps latestHtml current while no browser is connected,
	// so reconnecting tabs get the live grid instead of a stale frame.
	.screen.Sync()
}

// renderTerminal copies a vt10x grid into a tcell screen and returns the
// cursor state.
func renderTerminal(
	 vt10x.Terminal,  tcell.Screen,
) (vt10x.Cursor, bool) {
	,  := .Size()
	 := .Cursor()
	 := .CursorVisible()

	,  := .Size()
	 := min(, )
	 := min(, )

	for  := 0;  < ; ++ {
		for  := 0;  < ; ++ {
			 := .Cell(, )
			 := .Char
			if  == 0 {
				 = ' '
			}
			.SetContent(, , , nil, vtStyle())
		}
	}

	return , 
}

// inputLoop forwards livepage keyboard and resize events to the PTY.
func ( *livepageBridge) () {
	for {
		 := .screen.PollEvent()
		if  == nil {
			return
		}

		switch ev := .(type) {
		case *tcell.EventResize:
			,  := .Size()
			_ = pty.Setsize(.ptmx, &pty.Winsize{
				Rows: uint16(),
				Cols: uint16(),
			})
			.termMu.Lock()
			.term.Resize(, )
			.termMu.Unlock()
			.dirty.Store(true)

		case *tcell.EventKey:
			if  := encodeKey(); len() > 0 {
				.writePTY()
			}
		}
	}
}

func ( *livepageBridge) ( []byte) {
	.writeMu.Lock()
	defer .writeMu.Unlock()

	_, _ = .ptmx.Write()
}

// vtStyle converts a vt10x glyph into a tcell style.
func vtStyle( vt10x.Glyph) tcell.Style {
	 := tcell.StyleDefault.
		Foreground(vtColor(.FG)).
		Background(vtColor(.BG))

	if .Mode&vtAttrBold != 0 {
		 = .Bold(true)
	}
	if .Mode&vtAttrItalic != 0 {
		 = .Italic(true)
	}
	if .Mode&vtAttrUnderline != 0 {
		 = .Underline(true)
	}
	if .Mode&vtAttrReverse != 0 {
		 = .Reverse(true)
	}

	return 
}

// vtColor converts a vt10x color into a tcell color.
func vtColor( vt10x.Color) tcell.Color {
	switch  {
	case vt10x.DefaultFG, vt10x.DefaultBG, vt10x.DefaultCursor:
		return tcell.ColorDefault
	}
	if  < 256 {
		return tcell.PaletteColor(int())
	}

	return tcell.NewHexColor(int32())
}

// displayAddr turns wildcard listen addresses into something clickable.
func displayAddr( net.Addr) string {
	, ,  := net.SplitHostPort(.String())
	if  != nil {
		return .String()
	}
	if  == "" ||  == "::" ||  == "0.0.0.0" {
		 = "localhost"
	}

	return net.JoinHostPort(, )
}