package debugger

import (
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	

	
	
	
	
	
	

	

	

	ammcp 
	am 
	
	
)

const (
	// TODO customize
	playInterval = 500 * time.Millisecond
	// TODO add param --max-clients
	maxClients      = 5000
	timeFormat      = "15:04:05.000000000"
	fastJumpAmount  = 50
	arrowThrottleMs = 200
	// arrowHoldWindowMs is the max gap between arrow key repeats which still
	// counts as holding the key.
	arrowHoldWindowMs = 500
	// arrowRepeatMs is the min interval between steps while an arrow key is
	// held (~20 transitions per second).
	arrowRepeatMs         = 50
	logUpdateDebounce     = 300 * time.Millisecond
	sidebarUpdateDebounce = time.Second
	searchAsTypeWindow    = 1500 * time.Millisecond
	heartbeatInterval     = 1 * time.Minute
	// heartbeatInterval = 5 * time.Second
	// msgMaxAge             = 0

	// maxMemMb = 100
	maxMemMb        = 50
	msgMaxThreshold = 300
	// max txs queued for scrolling the timelines
	scrollTxThrottle = 3
	logFile          = "log.md"
)

type Client struct {
	*server.Client

	CursorTx1       int
	ReaderCollapsed bool
	SelectedState   string
	// extracted log entries per tx ID
	// TODO GC when all entries are closedAt and the first client's tx is later
	//  than the latest closedAt; whole tx needs to be disposed at the same time
	LogReader map[string][]*types.LogReaderEntry

	logRenderedCursor1    int
	logRenderedLevel      am.LogLevel
	logRenderedFilters    *types.Filters
	logRenderedGroup      string
	logRenderedFilterOut  string
	logRenderedTimestamps bool
	logReaderMx           sync.Mutex
}

func init() {
	gob.Register(server.Exportable{})
	gob.Register(am.Relation(0))
}

func newClient( string,  *dbg.DbgMsgStruct) *Client {
	 := &Client{
		Client:    server.NewClient(, ),
		LogReader: make(map[string][]*types.LogReaderEntry),
	}

	return 
}

func newClientExported( string,  *server.Exportable) *Client {
	 := &Client{
		Client:    server.NewClient(, .MsgStruct),
		LogReader: make(map[string][]*types.LogReaderEntry),
	}
	.Exportable = 

	// backward compatibility
	if .Exportable.Markers == nil {
		.Exportable.Markers = make(map[string]struct{})
	}

	return 
}

func ( *Client) ( string,  *types.LogReaderEntry) int {
	.logReaderMx.Lock()
	defer .logReaderMx.Unlock()

	.LogReader[] = append(.LogReader[], )

	return len(.LogReader[]) - 1
}

func ( *Client) ( string,  int) *types.LogReaderEntry {
	.logReaderMx.Lock()
	defer .logReaderMx.Unlock()

	,  := .LogReader[]
	if ! ||  >= len() {
		return nil
	}

	return []
}

// ///// ///// /////

// ///// SSH

// ///// ///// /////

func ( ssh.Session) (tcell.Screen, error) {
	, ,  := .Pty()
	if ! {
		return nil, errors.New("no pty requested")
	}
	,  := terminfo.LookupTerminfo(.Term)
	if  != nil {
		return nil, 
	}
	,  := tcell.NewTerminfoScreenFromTtyTerminfo(&tty{
		Session: ,
		size:    .Window,
		ch:      ,
	}, )
	if  != nil {
		return nil, 
	}
	return , nil
}

type tty struct {
	ssh.Session
	size     ssh.Window
	ch       <-chan ssh.Window
	resizecb func()
	mu       sync.Mutex
}

func ( *tty) () error {
	go func() {
		for  := range .ch {
			.mu.Lock()
			.size = 
			.notifyResize()
			.mu.Unlock()
		}
	}()
	return nil
}

func ( *tty) () error {
	return nil
}

func ( *tty) () error {
	return nil
}

func ( *tty) () ( tcell.WindowSize,  error) {
	.mu.Lock()
	defer .mu.Unlock()

	return tcell.WindowSize{
		Width:  .size.Width,
		Height: .size.Height,
	}, nil
}

func ( *tty) ( func()) {
	.mu.Lock()
	defer .mu.Unlock()

	.resizecb = 
}

func ( *tty) () {
	if .resizecb != nil {
		.resizecb()
	}
}

// ///// ///// /////

// ///// MISC

// ///// ///// /////

// openURL opens the specified URL in the default browser of the user.
// https://gist.github.com/sevkin/9798d67b2cb9d07cb05f89f14ba682f8
func openURL( string) error {
	var  string
	var  []string

	switch runtime.GOOS {
	case "windows":
		 = "cmd.exe"
		 = []string{
			"/c", "rundll32", "url.dll,FileProtocolHandler",
			strings.ReplaceAll(, "&", "^&"),
		}
	case "darwin":
		 = "open"
		 = []string{}
	default:
		if isWSL() {
			 = "cmd.exe"
			 = []string{"start", }
		} else {
			 = "xdg-open"
			 = []string{}
		}
	}

	 := exec.Command(, ...)
	 := .Start()
	if  != nil {
		return 
	}
	 = .Wait()
	if  != nil {
		return 
	}

	return nil
}

// isWSL checks if the Go program is running inside Windows Subsystem for Linux
func isWSL() bool {
	,  := exec.Command("uname", "-r").Output()
	if  != nil {
		return false
	}
	return strings.Contains(strings.ToLower(string()), "microsoft")
}

type MarkerItem struct {
	ClientId string
	TxId     string
	Time     time.Time
}

// ///// ///// /////

// ///// MCP SERVER

// ///// ///// /////

type mcpServer struct {
	*ammcp.Server
	d *Debugger
}

func newMcpServer( *Debugger) (*mcpServer, error) {
	,  := ammcp.New(.Mach, ammcp.Opts{
		Name: "am-dbg",
		Desc: "MCP to control the asyncmachine-go TUI debugger. " +
			"The double-line border panel is currently focused. " +
			"Most features are accessible via ToggleTool.",
		MutCallback: func( context.Context) error {
			 := .Mach.Eval("MCPTool", func() {
				.hRedrawFull(false)
			}, )
			if ! {
				return am.ErrEvalTimeout
			}
			return nil
		},
		StatesInclude:  states.DebuggerGroups.Mcp,
		StatesReadonly: states.DebuggerGroups.McpReadonly,
		Args:           types.ArgsRpc,
		CallSignatures: types.StateCalls,
		Version:        .params.Version,
	})
	if  != nil {
		return nil, 
	}

	// bind keys from keyboard.go
	 := slices.Collect(maps.Keys(.getKeystrokes()))
	 := mcp.NewTool(
		"Keystroke",
		mcp.WithDescription("Press a predefined key combination"),
		mcp.WithString(
			"key",
			mcp.Required(),
			mcp.Description("Name of the state to add"),
			mcp.Enum(...),
		),
	)
	// any key combo
	 := mcp.NewTool(
		"PressKey",
		mcp.WithDescription("Press any key combination"),
		mcp.WithString(
			"key",
			mcp.Required(),
			mcp.Description(
				"Key or key combination (e.g. 'enter', 'tab', 'shift+tab', "+
					"'alt+h', 'ctrl+q', 'up', 'down')"),
		),
	)
	 := mcp.NewTool(
		"TypeText",
		mcp.WithDescription("Type text into the focused TUI input or view"),
		mcp.WithString(
			"text",
			mcp.Required(),
			mcp.Description("Text to type"),
		),
	)

	// mouse events
	 := mcp.NewTool(
		"MouseClick",
		mcp.WithDescription(
			"Simulate a mouse left click at a grid position (x, y)"),
		mcp.WithNumber(
			"x",
			mcp.Required(),
			mcp.Description("X coordinate (column, 0-indexed)"),
		),
		mcp.WithNumber(
			"y",
			mcp.Required(),
			mcp.Description("Y coordinate (row, 0-indexed)"),
		),
	)
	 := mcp.NewTool(
		"MouseScroll",
		mcp.WithDescription("Simulate mouse scrolling at a grid position (x, y)"),
		mcp.WithNumber(
			"x",
			mcp.Required(),
			mcp.Description("X coordinate (column, 0-indexed)"),
		),
		mcp.WithNumber(
			"y",
			mcp.Required(),
			mcp.Description("Y coordinate (row, 0-indexed)"),
		),
		mcp.WithString(
			"direction",
			mcp.Required(),
			mcp.Description("Scroll direction ('up', 'down', 'left', 'right')"),
			mcp.Enum("up", "down", "left", "right"),
		),
		mcp.WithNumber(
			"amount",
			mcp.Description("Number of scroll steps (default: 1)"),
			mcp.DefaultNumber(1),
		),
	)

	// TUI

	 := mcp.NewTool(
		"TextScreen",
		mcp.WithDescription("Get text content of the TUI screen"),
	)
	 := mcp.NewTool(
		"TextLogReader",
		mcp.WithDescription("Get text content of the Log Reader pane"),
	)
	 := mcp.NewTool(
		"TextHelp",
		mcp.WithDescription("Get text content of the Help dialog"),
	)
	 := mcp.NewTool(
		"TextLog",
		mcp.WithDescription("Get text content of the current log buffer"),
	)
	 := mcp.NewTool(
		"TextClients",
		mcp.WithDescription("Get a full clients list"),
	)
	 := mcp.NewTool(
		"NetworkGraph",
		mcp.WithDescription("Get an XML of the network graph"),
	)
	 := mcp.NewTool(
		"Transition Steps",
		mcp.WithDescription(
			"Get a markdown sequence diagram of the transition steps",
		),
	)
	 := mcp.NewTool(
		"SerializedMachine",
		mcp.WithDescription(
			"Get a YAML of the serialized machine state",
		),
	)

	// methods

	 := mcp.NewTool("GoToMachAddr",
		mcp.WithDescription("Show a specific machine, transition, or mach time"),
		mcp.WithString(
			"url",
			mcp.Required(),
			mcp.Description("Address to go to"),
		))

	// server
	 := &mcpServer{
		Server: ,
		d:      ,
	}

	// bind handlers
	.Mcp.AddTool(, .textScreen)
	.Mcp.AddTool(, .textReader)
	.Mcp.AddTool(, .textHelp)
	.Mcp.AddTool(, .textLog)
	.Mcp.AddTool(, .textClients)
	.Mcp.AddTool(, .netGraph)
	.Mcp.AddTool(, .txSteps)
	.Mcp.AddTool(, .serializedMach)
	.Mcp.AddTool(, .goToMachAddr)
	.Mcp.AddTool(, .pressKey)
	.Mcp.AddTool(, .pressKey)
	.Mcp.AddTool(, .typeText)
	.Mcp.AddTool(, .mouseLeftClick)
	.Mcp.AddTool(, .mouseScroll)

	return , nil
}

func ( *mcpServer) (
	 context.Context,  mcp.CallToolRequest,
) (*mcp.CallToolResult, error) {
	,  := .RequireString("url")
	if  != nil {
		return mcp.NewToolResultError(.Error()), nil
	}
	,  := types.ParseMachUrl()
	if  != nil {
		return mcp.NewToolResultError(.Error()), nil
	}
	.d.GoToMachAddress(, false, false)

	return mcp.NewToolResultText("ok"), nil
}

func ( *mcpServer) (
	 context.Context,  mcp.CallToolRequest,
) (*mcp.CallToolResult, error) {
	// check if reader visible
	if .d.Mach.Not1(ss.LogReaderVisible) {
		return mcp.NewToolResultError(fmt.Sprintf(
			"state %s not active", ss.LogReaderVisible,
		)), nil
	}

	return mcp.NewToolResultText(.d.LogReaderText()), nil
}

func ( *mcpServer) (
	 context.Context,  mcp.CallToolRequest,
) (*mcp.CallToolResult, error) {
	var  string
	.d.Mach.Eval("textScreen", func() {
		 = .d.App.ScreenText()
	}, )

	return mcp.NewToolResultText(), nil
}

func ( *mcpServer) (
	 context.Context,  mcp.CallToolRequest,
) (*mcp.CallToolResult, error) {
	var  string
	.d.Mach.Eval("textHelp", func() {
		 = textViewToText(.d.helpDialogLeft) + "\n\n" +
			textViewToText(.d.helpDialogRight)
	}, )

	return mcp.NewToolResultText(), nil
}

func ( *mcpServer) (
	 context.Context,  mcp.CallToolRequest,
) (*mcp.CallToolResult, error) {
	 := *.d.Params.Load()
	if !.OutputLog {
		return mcp.NewToolResultError("--output-log not set"), nil
	}

	,  := os.ReadFile(path.Join(.OutputDir, logFile))
	if  != nil {
		return nil, 
	}
	return mcp.NewToolResultText(string()), nil
}

func ( *mcpServer) (
	 context.Context,  mcp.CallToolRequest,
) (*mcp.CallToolResult, error) {
	 := *.d.Params.Load()
	if !.OutputClients {
		return mcp.NewToolResultError("--output-clients not set"), nil
	}

	,  := os.ReadFile(path.Join(.OutputDir, "clients.md"))
	if  != nil {
		return nil, 
	}
	return mcp.NewToolResultText(string()), nil
}

func ( *mcpServer) (
	 context.Context,  mcp.CallToolRequest,
) (*mcp.CallToolResult, error) {
	 := *.d.Params.Load()
	if !.OutputLog {
		return mcp.NewToolResultError("--output-clients not set"), nil
	}

	,  := os.ReadFile(path.Join(.OutputDir, "graph.xml"))
	if  != nil {
		return nil, 
	}
	return mcp.NewToolResultText(string()), nil
}

func ( *mcpServer) (
	 context.Context,  mcp.CallToolRequest,
) (*mcp.CallToolResult, error) {
	 := *.d.Params.Load()
	if !.OutputTx {
		return mcp.NewToolResultError("--output-tx not set"), nil
	}

	,  := os.ReadFile(path.Join(.OutputDir, "tx.md"))
	if  != nil {
		return nil, 
	}
	return mcp.NewToolResultText(string()), nil
}

func ( *mcpServer) (
	 context.Context,  mcp.CallToolRequest,
) (*mcp.CallToolResult, error) {
	 := *.d.Params.Load()
	if !.OutputMach {
		return mcp.NewToolResultError("--output-mach not set"), nil
	}

	,  := os.ReadFile(path.Join(.OutputDir, "mach.yml"))
	if  != nil {
		return nil, 
	}
	return mcp.NewToolResultText(string()), nil
}

func ( *mcpServer) (
	 context.Context,  mcp.CallToolRequest,
) (*mcp.CallToolResult, error) {
	,  := .RequireString("key")
	if  != nil {
		return mcp.NewToolResultError(.Error()), nil
	}

	, , ,  := cbind.Decode()
	if  != nil {
		return mcp.NewToolResultError(.Error()), nil
	}

	.d.App.QueueEvent(tcell.NewEventKey(, , ))
	return mcp.NewToolResultText("ok"), nil
}

func ( *mcpServer) (
	 context.Context,  mcp.CallToolRequest,
) (*mcp.CallToolResult, error) {
	,  := .RequireString("text")
	if  != nil {
		return mcp.NewToolResultError(.Error()), nil
	}

	for ,  := range  {
		var (
			 tcell.Key     = tcell.KeyRune
			 tcell.ModMask = tcell.ModNone
		)
		switch  {
		case '\n', '\r':
			 = tcell.KeyEnter
		case '\t':
			 = tcell.KeyTab
		}
		.d.App.QueueEvent(tcell.NewEventKey(, , ))
	}

	return mcp.NewToolResultText("ok"), nil
}

func ( *mcpServer) (
	 context.Context,  mcp.CallToolRequest,
) (*mcp.CallToolResult, error) {
	,  := .RequireInt("x")
	if  != nil {
		return mcp.NewToolResultError(.Error()), nil
	}
	,  := .RequireInt("y")
	if  != nil {
		return mcp.NewToolResultError(.Error()), nil
	}

	.d.App.QueueEvent(
		tcell.NewEventMouse(, , tcell.ButtonPrimary, tcell.ModNone))
	.d.App.QueueEvent(tcell.NewEventMouse(, , tcell.ButtonNone, tcell.ModNone))

	return mcp.NewToolResultText("ok"), nil
}

func ( *mcpServer) (
	 context.Context,  mcp.CallToolRequest,
) (*mcp.CallToolResult, error) {
	,  := .RequireInt("x")
	if  != nil {
		return mcp.NewToolResultError(.Error()), nil
	}
	,  := .RequireInt("y")
	if  != nil {
		return mcp.NewToolResultError(.Error()), nil
	}
	,  := .RequireString("direction")
	if  != nil {
		return mcp.NewToolResultError(.Error()), nil
	}
	 := .GetInt("amount", 1)
	if  <= 0 {
		 = 1
	}

	var  tcell.ButtonMask
	switch strings.ToLower() {
	case "up":
		 = tcell.WheelUp
	case "down":
		 = tcell.WheelDown
	case "left":
		 = tcell.WheelLeft
	case "right":
		 = tcell.WheelRight
	default:
		return mcp.NewToolResultError("invalid direction: " + ), nil
	}

	for  := 0;  < ; ++ {
		.d.App.QueueEvent(tcell.NewEventMouse(, , , tcell.ModNone))
	}

	return mcp.NewToolResultText("ok"), nil
}

// ///// ///// /////

// ///// LIVEPAGE

// ///// ///// /////

// livepageTracker counts livepage WebSocket connections. The page's WS handler
// blocks for the whole lifetime of a connection.
type livepageTracker struct {
	handler http.Handler
	count   atomic.Int32
	onEmpty func()
}

func ( *livepageTracker) ( http.ResponseWriter,  *http.Request) {
	 := .URL.Path == livepagePrefix+livepage.PathWs
	if  {
		.count.Add(1)
		defer func() {
			if .count.Add(-1) == 0 && .onEmpty != nil {
				.onEmpty()
			}
		}()
	}
	.handler.ServeHTTP(, )
}

// Clients returns the number of connected browsers.
func ( *livepageTracker) () int {
	return int(.count.Load())
}