package server

// TODO rewrite to a better protocol with
//  - everything from the reader
//  - graphs

import (
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	

	
	

	
	
	amhelp 
	am 
	
	
	
)

var ss = states.DebuggerStates
var Pass = am.Pass

type A = types.A

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

// ///// CLIENT

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

type Exportable struct {
	// TODO refac to MsgSchema
	// TODO version schemas
	MsgStruct *dbg.DbgMsgStruct
	MsgTxs    []*dbg.DbgMsgTx
	// TODO clean up on GC
	Markers map[string]struct{}
	Version string
}

type Client struct {
	// bits which get saved into the go file
	*Exportable

	// current transition, 1-based, mirrors the slider (eg 1 means tx.ID == 0)
	// TODO atomic
	ReaderCollapsed bool
	Id              string
	MTimeSum        uint64
	SelectedGroup   string
	Connected       atomic.Bool
	ConnId          string
	SchemaHash      string
	// processed list of filtered tx _indexes_
	MsgTxsFiltered []int
	// cache of processed log entries
	LogMsgs [][]*am.LogEntry
	// indexes of txs with errors, desc order for bisects
	// TOOD refresh on GC
	Errors []int
	// processed
	MsgTxsParsed    []*types.MsgTxParsed
	MsgSchemaParsed *types.MsgSchemaParsed

	txCache   map[string]int
	txCacheMx sync.Mutex
}

func ( string,  *dbg.DbgMsgStruct) *Client {
	 := &Client{
		Id:         .ID,
		ConnId:     ,
		SchemaHash: amhelp.SchemaHash(.States),
		Exportable: &Exportable{
			MsgStruct: ,
			Markers:   make(map[string]struct{}),
		},
	}
	.ParseSchema()

	return 
}

func ( *Client) ( string) bool {
	,  := .Markers[]
	return 
}

func ( *Client) ( string,  bool) {
	if  {
		.Markers[] = struct{}{}
	} else {
		delete(.Markers, )
	}
}

func ( *Client) () {
	.txCache = nil
}

func ( *Client) () time.Time {
	if len(.MsgTxs) == 0 {
		return time.Time{}
	}

	return *.MsgTxs[len(.MsgTxs)-1].Time
}

func ( *Client) (,  int) bool {
	if slices.Contains(.Errors, ) {
		return true
	}

	// see TestHadErrSince
	 := sort.Search(len(.Errors), func( int) bool {
		return .Errors[] < 
	})

	if  >= len(.Errors) {
		return false
	}

	return -.Errors[] < 
}

func ( *Client) ( uint64) int {
	 := len(.MsgTxs)
	if  == 0 {
		return -1
	}

	 := sort.Search(, func( int) bool {
		return .MsgTxs[].QueueTick >= 
	})

	if  ==  {
		 =  - 1
	}

	return 
}

// TxAtStateTick returns the index of the first transition after which [state]
// reached the [tick] of its clock, or the closest later transition.
func ( *Client) ( string,  uint64) int {
	 := .MsgStruct.StatesIndex
	if slices.Index(, ) == -1 {
		return -1
	}

	 := len(.MsgTxs)
	if  == 0 {
		return -1
	}

	 := sort.Search(, func( int) bool {
		return .MsgTxs[].Clock(, ) >= 
	})

	if  ==  {
		 =  - 1
	}

	return 
}

func ( *Client) ( time.Time) int {
	 := len(.MsgTxs)
	if  == 0 {
		return -1
	}

	 := sort.Search(, func( int) bool {
		 := .MsgTxs[].Time
		return .After() || .Equal()
	})

	if  ==  {
		 =  - 1
	}
	 := .MsgTxs[]

	// pick the closer one
	if  > 0 && .Time.Sub() > .Sub(*.MsgTxs[-1].Time) {
		return 
	} else {
		return 
	}
}

func ( *Client) ( am.S) []int {
	return helpers.StatesToIndexes(.MsgStruct.StatesIndex, )
}

func ( *Client) ( []int) am.S {
	return helpers.IndexesToStates(.MsgStruct.StatesIndex, )
}

func ( *Client) ( string) []int {
	return .MsgStruct.StatesIndex.Index(strings.Split(, " "))
}

// TxIndex returns the index of transition ID [id] or -1 if not found.
func ( *Client) ( string) int {
	.txCacheMx.Lock()
	defer .txCacheMx.Unlock()

	if .txCache == nil {
		.txCache = make(map[string]int)
	}
	if ,  := .txCache[];  {
		return 
	}

	for ,  := range .MsgTxs {
		if .ID ==  {
			.txCache[] = 
			return 
		}
	}

	return -1
}

func ( *Client) ( int) *dbg.DbgMsgTx {
	if  < 0 ||  >= len(.MsgTxs) {
		return nil
	}

	return .MsgTxs[]
}

func ( *Client) ( int) *types.MsgTxParsed {
	if  < 0 ||  >= len(.MsgTxsParsed) {
		return nil
	}

	return .MsgTxsParsed[]
}

// TxExecutedBy returns the execution transition for a queued transition
func ( *Client) ( int) *dbg.DbgMsgTx {
	 := .MsgTxs[]
	if  == nil || !.IsQueued {
		return nil
	}
	var  *dbg.DbgMsgTx

	// DEBUG
	// // look into the future TODO links to the wrong one
	// for iii := c.CursorTx1; iii < len(c.MsgTxs); iii++ {
	// 	check := c.MsgTxs[iii]
	// 	txCalled := tx.CalledStateNames(statesIndex)
	// 	checkCalled := check.CalledStateNames(statesIndex)
	// 	if !check.IsQueued && am.StatesEqual(txCalled, checkCalled) {
	// 		d.Mach.Log("exec tx.MQT: %d, check.QT: %d",
	// 			tx.MutQueueTick, check.QueueTick)
	// 		d.Mach.Log("exec tx.Called: %s, check.Called: %s",
	// 			txCalled,
	// 			checkCalled)
	// 	}
	// }

	// look into the future
	for  :=  + 1;  < len(.MsgTxs); ++ {
		 := .MsgTxs[]

		if .IsQueued {
			continue
		}

		if .QueueTick == .MutQueueTick ||
			(.MutQueueToken > 0 && .MutQueueToken == .MutQueueToken) {

			 = 
			break
		}
	}

	return 
}

func ( *Client) ( uint64) int {
	,  := slices.BinarySearchFunc(.MsgTxsParsed,
		&types.MsgTxParsed{TimeSum: }, func(,  *types.MsgTxParsed) int {
			if .TimeSum < .TimeSum {
				return -1
			} else if .TimeSum > .TimeSum {
				return 1
			}

			return 0
		})

	if ! {
		return 0
	}

	return 
}

func ( *Client) ( int) int {
	if  == 0 {
		return 0
	}

	return slices.Index(.MsgTxsFiltered, -1)
}

func ( *Client) () {
	// defaults
	 := .MsgStruct
	 := &types.MsgSchemaParsed{
		GroupsOrder: []string{"all"},
		Groups: map[string]am.S{
			"all": .StatesIndex,
		},
	}
	.MsgSchemaParsed = 
	.Hash = amhelp.SchemaHash(.States)

	if len(.GroupsOrder) == 0 {
		return
	}

	// schema groups
	 := false
	 := am.S{}
	for ,  := range .GroupsOrder {
		// TODO terrible
		 := strings.TrimSuffix(, "StatesDef")
		if  == "self" {
			 = "- self"
		} else if  {
			 = "- " + 
		}
		.GroupsOrder = append(.GroupsOrder, )
		.Groups[] = .IndexesToStates(.Groups[])

		if  {
			// merge with prev groups TODO why? breaks inheriting from 2 sources
			.Groups[] = slices.Concat(.Groups[], )
			 = .Groups[]
		}

		if  == "self" {
			 = true
		}
	}
}

// TODO enable when needed
// func (c *Client) txByQueueTick(qTick uint64) int {
// 	idx, ok := slices.BinarySearchFunc(c.MsgTxs,
// 		&telemetry.DbgMsgTx{QueueTick: qTick},
// 		func(i, j *telemetry.DbgMsgTx) int {
// 			if i.QueueTick < j.QueueTick {
// 				return -1
// 			} else if i.QueueTick > j.QueueTick {
// 				return 1
// 			}
//
// 			return 0
// 		})
//
// 	if !ok {
// 		return 0
// 	}
//
// 	return idx
// }
//
// func (c *Client) txByMutQueueTick(qTick uint64) int {
// 	idx, ok := slices.BinarySearchFunc(c.MsgTxs,
// 		&telemetry.DbgMsgTx{MutQueueTick: qTick},
// 		func(i, j *telemetry.DbgMsgTx) int {
// 			if i.MutQueueTick < j.MutQueueTick {
// 				return -1
// 			} else if i.MutQueueTick > j.MutQueueTick {
// 				return 1
// 			}
//
// 			return 0
// 		})
//
// 	if !ok {
// 		return 0
// 	}
//
// 	return idx
// }

// TODO
// func NewClient()

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

// ///// SERVER

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

const (
	fwdBackoffMin  = 500 * time.Millisecond
	fwdBackoffMax  = 5 * time.Second
	fwdDialTimeout = 5 * time.Second
	fwdCallTimeout = 5 * time.Second
	// fwdDialWait is how long [fwdConn.Call] waits for an in-flight dial (and
	// its replays) before dropping the msg. Kept short, so a black-holed dial
	// can't stall the other fwd targets.
	fwdDialWait = 200 * time.Millisecond
	// fwdReplayMaxDefault is the default number of recent tx msgs kept in
	// memory for replaying to (re)connected fwd targets. Overridable via the
	// --fwd-replay-max CLI param.
	fwdReplayMaxDefault = 100
)

// fwdConn is a lazily- and re-dialed RPC connection to a forwarding target.
// It survives target downtime (both at startup and mid-stream) by redialing
// in the background with an exponential backoff, instead of failing the
// whole dbg server or permanently giving up on a forward target.
//
// Failing targets are isolated: callers treat fwd errors as non-fatal, and
// both dialing and calls are bounded with timeouts, so a missing or hung
// target cannot stall the other fwd targets nor the sending client.
type fwdConn struct {
	addr string
	mach *am.Machine
	// replayMax is the number of recent tx msgs kept per stream, see
	// [fwdReplayMaxDefault].
	replayMax int

	mx       sync.Mutex
	cli      *rpc.Client
	dialing  bool
	backoff  time.Duration
	nextDial time.Time
	// dialDone is closed when the in-flight dial attempt finishes, so callers
	// can wait for it (and its replays) instead of dropping msgs.
	// See [fwdConn.Call].
	dialDone chan struct{}
	// streams are the replay sources of this dbg server, one per accepted
	// conn, injected on accept and removed on disconnect.
	// See [fwdConn.addStream].
	streams []*RPCServer
	// detached keeps the streams of disconnected conns, so their buffered
	// msgs stay replayable until evicted by the [fwdConn.replayMax] budget.
	// See [fwdConn.removeStream].
	detached []*RPCServer
}

// newFwdConn creates a fwdConn and kicks off the initial (non-blocking)
// dial.
func newFwdConn( *am.Machine,  string,  int) *fwdConn {
	 := &fwdConn{
		addr:      ,
		mach:      ,
		replayMax: ,
		backoff:   fwdBackoffMin,
	}
	go .dial()

	return 
}

// retry schedules another dial attempt, doubling the backoff (capped at
// fwdBackoffMax). Requires f.mx to be held by the caller.
func ( *fwdConn) ( error) {
	 := .backoff
	.nextDial = time.Now().Add()
	.backoff *= 2
	if .backoff > fwdBackoffMax {
		.backoff = fwdBackoffMax
	}
	.mach.Log("dbg fwd to %s failed, retrying in %s: %s",
		.addr, , )
	go func() {
		time.Sleep()
		.dial()
	}()
}

// dial (re)connects, replays known client schemas and recent msgs as the first
// messages on the fresh connection, and resets the backoff on success. Safe to
// call concurrently. f.mx is not held while dialing, so a hanging target cannot
// block calls to the other targets.
func ( *fwdConn) () {
	.mx.Lock()
	if .cli != nil || .dialing || time.Now().Before(.nextDial) {
		.mx.Unlock()
		return
	}
	.dialing = true
	 := make(chan struct{})
	.dialDone = 
	.mx.Unlock()

	// waiters in [fwdConn.Call] get released on every path, after f.cli is set
	defer close()

	,  := dialFwd(.addr)
	if  == nil {
		// replay known client schemas first, so a (re)connected target learns
		// about clients it missed while this fwd link was down
		 = .pushClientSchemas()
		if  == nil {
			// then the recent tx msgs it missed
			 = .pushClientMsgs()
		}
		if  != nil {
			 = fmt.Errorf("replay: %w", )
		}
	}

	.mx.Lock()
	.dialing = false
	if  == nil {
		.mach.Log("dbg fwd to %s connected", .addr)
		.cli = 
		.backoff = fwdBackoffMin
		.mx.Unlock()
		return
	}
	if  != nil {
		_ = .Close()
	}
	.retry()
	.mx.Unlock()
}

// dialFwd connects to addr with a timeout, so a missing or black-holed target
// cannot hang the dialer.
func dialFwd( string) (*rpc.Client, error) {
	,  := net.DialTimeout("tcp", , fwdDialTimeout)
	if  != nil {
		return nil, 
	}

	return rpc.NewClient(), nil
}

// call performs an RPC call with a timeout, so a half-open (accepted but
// unresponsive) target cannot hang the caller. f.mx is not required.
func ( *fwdConn) (
	 *rpc.Client,  string, ,  any,
) error {
	// client.Call has no timeout, so use Go + a timer to survive half-open
	// (accepted but unresponsive) targets
	 := .Go(, , , make(chan *rpc.Call, 1))
	select {
	case  := <-.Done:
		return .Error
	case <-time.After(fwdCallTimeout):
		return fmt.Errorf("dbg fwd to %s: call timeout after %s",
			.addr, fwdCallTimeout)
	}
}

// Call forwards an RPC call over the current connection. If a dial (and its
// replays) is in flight, it waits for it first. If disconnected, or the call
// fails or times out, it triggers a reconnect with a backoff and returns an
// error, leaving the caller to drop the message. Callers must treat errors as
// non-fatal for the other fwd targets.
func ( *fwdConn) ( string, ,  any) error {
	.mx.Lock()
	 := .cli
	 := .dialDone
	.mx.Unlock()

	// wait for an in-flight (re)connect, incl. its schema and msg replays,
	// instead of dropping the msg - otherwise anything sent during a replay
	// (eg a new client's schema) would be lost until the next reconnect
	if  == nil &&  != nil {
		select {
		case <-:
		case <-time.After(fwdDialWait):
		}
		.mx.Lock()
		 = .cli
		.mx.Unlock()
	}

	if  == nil {
		go .dial()
		return fmt.Errorf("dbg fwd to %s: not connected", .addr)
	}

	 := .call(, , , )

	if  != nil {
		.mx.Lock()
		if .cli ==  {
			_ = .Close()
			.cli = nil
		}
		.retry()
		.mx.Unlock()
	}

	return 
}

// New initializes listeners, fwd conns, and returns unstated servers.
func (
	 *am.Machine,  string,  func() *types.Params,
) (cmux.CMux, *http.Server, error) {
	// TODO extract conns, write a sibling impl on AM
	// TODO dont listen in WASM

	 := ()
	var  error
	gob.Register(am.Relation(0))
	gob.Register(Exportable{})
	if  == "" {
		 = dbg.DbgAddr
	}
	, ,  := net.SplitHostPort()
	,  := strconv.Atoi()
	,  := net.Listen("tcp", )
	if  != nil {
		return nil, nil, 
	}
	.Log("dbg server started at %s", )

	// connect to other instances (non-blocking, reconnects with a backoff)
	// TODO add mutable FwdData setter
	 := .FwdReplayMax
	if  <= 0 {
		 = fwdReplayMaxDefault
	}
	 := make([]*fwdConn, len(.FwdData))
	for ,  := range .FwdData {
		[] = newFwdConn(, , )
	}

	// first cmux for tcp
	 := cmux.New()
	 := .Match(cmux.Any())
	go tcpAccept(, , )

	// HTTP and WS on port+1
	var  *http.Server
	if .UiWeb {
		 := fmt.Sprintf("%s:%d",
			[:strings.LastIndex(, ":")], +1)
		 := http.ServeMux{}
		.HandleFunc("/{$}", func( http.ResponseWriter,  *http.Request) {
			httpHandlerIndex(, , , ())
		})
		.Handle("/", http.FileServer(http.Dir(.OutputDir)))

		// diagrams

		.HandleFunc("/viewer/mach",
			newDiagHandler(, types.DiagramTypeMach))
		.HandleFunc("/viewer/mach.svg",
			newDiagHandler(, types.DiagramTypeMach))
		.HandleFunc("/viewer/mach.ws",
			newWsDiagHandler(, types.DiagramTypeMach))

		.HandleFunc("/viewer/state",
			newDiagHandler(, types.DiagramTypeState))
		.HandleFunc("/viewer/state.svg",
			newDiagHandler(, types.DiagramTypeState))
		.HandleFunc("/viewer/state.ws",
			newWsDiagHandler(, types.DiagramTypeState))

		.HandleFunc("/viewer/steps",
			newDiagHandler(, types.DiagramTypeSteps))
		.HandleFunc("/viewer/steps.svg",
			newDiagHandler(, types.DiagramTypeSteps))
		.HandleFunc("/viewer/steps.ws",
			newWsDiagHandler(, types.DiagramTypeSteps))

		.HandleFunc("/viewer/graph",
			newDiagHandler(, types.DiagramTypeGraph))
		.HandleFunc("/viewer/graph.svg",
			newDiagHandler(, types.DiagramTypeGraph))
		.HandleFunc("/viewer/graph.ws",
			newWsDiagHandler(, types.DiagramTypeGraph))

		.HandleFunc("/dbg.ws", func( http.ResponseWriter,  *http.Request) {
			wsDbgHandler(, , , )
		})

		 = &http.Server{
			Handler: &,
			Addr:    ,
		}
	}

	return , , nil
}

// TODO rename to RPCServer (compat break)
type RPCServer struct {
	Mach *am.Machine
	// TODO ConnId
	ConnID string
	FwdTo  []*fwdConn
	// replayMax is the max number of recent tx msgs to buffer for replay,
	// copied from the fwd targets. See [fwdReplayMaxDefault].
	replayMax int

	// txBatch batches incoming tx msgs into [ss.ClientMsg] mutations, see
	// [RPCServer.flushTxs].
	txBatch *amhelp.Batch[txBatchItem]

	// clientMsgs holds the last [RPCServer.replayMax] tx msgs of this conn's
	// stream (a direct client, or all clients behind a fwd link), for replaying
	// to (re)connected fwd targets. Copy-on-write, see [RPCServer.appendMsg].
	clientMsgs atomic.Pointer[[]*DbgMsgTx]

	// clientSchemas holds the latest schema of each client of this conn's
	// stream, keyed by machine ID. A new schema always replaces the old one.
	// Copy-on-write, see [RPCServer.setSchema].
	clientSchemas atomic.Pointer[map[string]*DbgMsgSchemaFwd]
}

type DbgMsgSchemaFwd struct {
	MsgStruct *dbg.DbgMsgStruct
	ConnId    string
}

// appendMsg buffers msg as one of the last [RPCServer.replayMax] msgs of this
// conn's stream, which get replayed to (re)connected fwd targets. Older msgs
// are dropped. Published snapshots are copy-on-write, so replaying needs no
// locks, and the CAS loop keeps concurrent appends (one goroutine per RPC call)
// safe.
func ( *RPCServer) ( *DbgMsgTx) {
	for {
		 := .clientMsgs.Load()
		var  []*DbgMsgTx
		if  != nil {
			 = slices.Clone(*)
		}

		// drop the oldest ones over the limit
		if .replayMax > 0 && len() >= .replayMax {
			 = [len()-.replayMax+1:]
		}
		 = append(, )

		if .clientMsgs.CompareAndSwap(, &) {
			return
		}
	}
}

// msgCount returns the number of buffered msgs of this conn.
func ( *RPCServer) () int {
	if  := .clientMsgs.Load();  != nil {
		return len(*)
	}

	return 0
}

// setSchema caches the latest schema of a client of this conn's stream, keyed
// by machine ID, replacing any older schema of that client. Published
// snapshots are copy-on-write, so replaying needs no locks, and the CAS loop
// keeps concurrent updates (one goroutine per RPC call) safe.
func ( *RPCServer) ( *DbgMsgSchemaFwd) {
	for {
		 := .clientSchemas.Load()
		 := make(map[string]*DbgMsgSchemaFwd)
		if  != nil {
			for ,  := range * {
				[] = 
			}
		}
		[.MsgStruct.ID] = 

		if .clientSchemas.CompareAndSwap(, &) {
			return
		}
	}
}

// clearSchemas drops all cached schemas of this conn, so a disconnected client
// is never resent to fwd targets. Buffered msgs are kept, see
// [fwdConn.removeStream].
func ( *RPCServer) () {
	.clientSchemas.Store(nil)
}

// addStream injects conn as a replay source for this target, so its schemas
// and buffered msgs get replayed on (re)connect. See [fwdConn.dial].
func ( *fwdConn) ( *RPCServer) {
	.mx.Lock()
	defer .mx.Unlock()

	.streams = append(.streams, )
}

// removeStream drops conn from the replay sources, but keeps it in [detached]
// so its buffered msgs stay replayable until evicted by the
// [fwdConn.replayMax] budget. Schemas are cleared by the caller, see
// [RPCServer.clearSchemas].
func ( *fwdConn) ( *RPCServer) {
	.mx.Lock()
	defer .mx.Unlock()

	for ,  := range .streams {
		if  ==  {
			.streams = append(.streams[:], .streams[+1:]...)
			break
		}
	}

	.detached = append(.detached, )

	// evict the oldest detached streams over the msgs budget
	 := 0
	for ,  := range .detached {
		 += .msgCount()
	}
	for  > .replayMax && len(.detached) > 0 {
		 -= .detached[0].msgCount()
		.detached = .detached[1:]
	}
}

// pushClientSchemas replays the schema of every currently connected client
// over cli, as the first messages on a freshly (re)connected fwd link, so
// the target learns about clients it missed while disconnected.
func ( *fwdConn) ( *rpc.Client) error {
	.mx.Lock()
	 := slices.Clone(.streams)
	.mx.Unlock()

	for ,  := range  {
		 := .clientSchemas.Load()
		if  == nil {
			continue
		}

		// deterministic order, so replays are stable
		 := make([]string, 0, len(*))
		for  := range * {
			 = append(, )
		}
		sort.Strings()

		for ,  := range  {
			 := (*)[]
			if  := .call(, "RPCServer.DbgMsgSchemaFwd", , nil);  != nil {
				return 
			}
		}
	}

	return nil
}

// pushClientMsgs replays the buffered tx msgs right after
// [fwdConn.pushClientSchemas] on a freshly (re)connected fwd link. It pushes
// everything, so the target is always fully caught up. Msgs of disconnected
// conns are replayed last, from [fwdConn.detached].
func ( *fwdConn) ( *rpc.Client) error {
	.mx.Lock()
	 := slices.Clone(.streams)
	 = append(, .detached...)
	.mx.Unlock()

	for ,  := range  {
		 := .clientMsgs.Load()
		if  == nil {
			continue
		}

		for ,  := range * {
			if  := .call(, "RPCServer.DbgMsgTxFwd", , nil);  != nil {
				return 
			}
		}
	}

	return nil
}

// TODO rename to RemoteMsgSchemaReceive (compat break)
func ( *RPCServer) (
	 *DbgMsgSchemaFwd,  *string,
) error {

	.Mach.Add1(ss.ConnectEvent, Pass(&A{
		MsgStruct: .MsgStruct,
		ConnId:    .ConnId,
		ClientId:  .MsgStruct.ID,
	}))

	// cache for fwd replay, a new schema replaces the old one of that client
	if len(.FwdTo) > 0 {
		.setSchema()
	}

	return nil
}

func ( *RPCServer) (
	 *dbg.DbgMsgStruct,  *string,
) error {

	.Mach.Add1(ss.ConnectEvent, Pass(&A{
		MsgStruct: ,
		ConnId:    .ConnID,
		ClientId:  .ID,
	}))

	// cache for fwd replay, a new schema replaces the old one of that client
	if len(.FwdTo) > 0 {
		.setSchema(&DbgMsgSchemaFwd{
			MsgStruct: ,
			ConnId:    .ConnID,
		})
	}

	// fwd to other instances (best effort), a missing target must not affect
	// the sender nor the other targets
	for ,  := range .FwdTo {
		 := DbgMsgSchemaFwd{
			MsgStruct: ,
			ConnId:    .ConnID,
		}
		// TODO const name
		// errors are logged and retried by the fwd conn itself
		_ = .Call("RPCServer.DbgMsgSchemaFwd", &, nil)
	}

	return nil
}

func ( *RPCServer) ( *dbg.DbgMsgTx,  *string) error {
	.enqueueTx(, .ConnID)

	return nil
}

// txBatchItem is a tx msg with its origin conn ID, batched before being
// pushed as [ss.ClientMsg].
type txBatchItem struct {
	MsgTx  *dbg.DbgMsgTx
	ConnId string
}

// enqueueTx batches a tx msg for the [ss.ClientMsg] mutation and forwards it
// to other instances (best effort).
func ( *RPCServer) ( *dbg.DbgMsgTx,  string) {
	 := time.Now()
	.Time = &
	.txBatch.Add(txBatchItem{MsgTx: , ConnId: })

	// fwd to other instances, outside the batch lock, so a slow fwd target
	// cannot stall the batch nor the other targets
	.fwdTx(, )
}

// flushTxs pushes a batch of tx msgs as a single [ss.ClientMsg] mutation.
func ( *RPCServer) ( []txBatchItem) {
	 := make([]*dbg.DbgMsgTx, len())
	 := make([]string, len())
	for ,  := range  {
		[] = .MsgTx
		[] = .ConnId
	}

	.Mach.Add1(ss.ClientMsg, Pass(&A{
		MsgsTx:  ,
		ConnIds: ,
	}))
}

// fwdTx forwards a message to all fwd targets, best effort. Errors are logged
// and retried by [fwdConn] itself; one failing target must not affect the
// others nor the sending client.
func ( *RPCServer) ( *dbg.DbgMsgTx,  string) {
	 := &DbgMsgTx{
		MsgTx:  ,
		ConnId: ,
	}

	// buffer recent msgs, so (re)connected targets can be caught up after
	// their schemas, see [fwdConn.pushClientMsgs]. Instances without fwd
	// targets pay nothing.
	if len(.FwdTo) > 0 {
		.appendMsg()
	}

	for ,  := range .FwdTo {
		// TODO const name
		_ = .Call("RPCServer.DbgMsgTxFwd", , nil)
	}
}

type DbgMsgTx struct {
	MsgTx  *dbg.DbgMsgTx
	ConnId string
}

// TODO rename to RemoteMsgTxReceive (compat break)
func ( *RPCServer) ( *DbgMsgTx,  *string) error {
	.enqueueTx(.MsgTx, .ConnId)

	return nil
}

func tcpAccept( net.Listener,  *am.Machine,  []*fwdConn) {
	// TODO restart on error
	// defer mach.PanicToErr(nil)

	for {
		,  := .Accept()
		if  != nil {
			// log.Println(err)
			.AddErr(, nil)
			continue
		}

		// handle the client
		go AcceptConn(, , )
	}
}

// AcceptConn accepts a std rpc connection, or alike.
func (
	 io.ReadWriteCloser,  *am.Machine,  []*fwdConn,
) {
	 := rpc.NewServer()
	 := utils.RandId(8)
	 := &RPCServer{
		Mach:   ,
		ConnID: ,
		FwdTo:  ,
	}
	.txBatch = &amhelp.Batch[txBatchItem]{
		Window: time.Second,
		Flush:  .flushTxs,
	}
	// all fwd targets share the same replay budget, see [newFwdConn]
	if len() > 0 {
		.replayMax = [0].replayMax
	}

	 := .Register()
	if  != nil {
		.Mach.AddErr(, nil)
		// TODO err msg
		fmt.Println()
		return
	}

	// inject the conn as a replay source, so fwd targets get its schemas and
	// buffered msgs on (re)connect. This happens before ServeConn, so no msg
	// of this conn can be missed by a replay.
	for ,  := range  {
		.addStream()
	}

	.ServeConn()

	// keep the buffered msgs replayable, but stop resending dead schemas
	.clearSchemas()
	for ,  := range  {
		.removeStream()
	}

	// TODO pass to range fwdTo (dedicated RPC method)
	.Mach.Add1(ss.DisconnectEvent, Pass(&A{
		ConnId: ,
	}))
}

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

// ///// WEB

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

// httpHandlerIndex lists --dir
func httpHandlerIndex(
	 http.ResponseWriter,  *http.Request,  *am.Machine,  *types.Params,
) {
	middleware()

	// Read directory contents
	,  := os.ReadDir(.OutputDir)
	if  != nil {
		.AddErr(, nil)
		http.Error(, "Failed to read directory", http.StatusInternalServerError)
		return
	}

	// compute addr TODO take from dbg instance
	 := ""
	if .ListenAddr != "-1" && .ListenAddr != "" {
		, ,  := net.SplitHostPort(.ListenAddr)
		 = 

		// global listen
		if  == "0.0.0.0" {
			,  := utils.GetGlobalUnicastIp()
			if  == nil {
				 = 
			}
		}

		if  == nil {
			,  := strconv.Atoi()
			 += fmt.Sprintf(":%d", +1)
		}
	}

	sort.Slice(, func(,  int) bool {
		if [].IsDir() != [].IsDir() {
			return [].IsDir()
		}
		return [].Name() < [].Name()
	})

	// Build HTML response
	.Header().Set("Content-Type", "text/html; charset=utf-8")
	fmt.Fprintf(, "<html><head><title>am-dbg --dir %s</title></head><body>",
		.OutputDir)
	fmt.Fprintf(, "<h1>am-dbg</h1><hr>")

	fmt.Fprintf(, "<h2>Pages</h2><hr><ul>")

	// diagrams
	if .OutputDiagrams != types.ParamsOutputDiagramsNone {
		fmt.Fprintf(, "<li><a href=\"/viewer/graph\">"+
			"Graph Diagram</a></li>")
		fmt.Fprintf(, "<li><a href=\"/viewer/mach\">"+
			"Machine Diagram</a></li>")
		fmt.Fprintf(, "<li><a href=\"/viewer/state\">"+
			"State Diagram</a></li>")
		fmt.Fprintf(, "<li><a href=\"/viewer/steps\">"+
			"Step Diagram</a></li>")
	}
	fmt.Fprintf(, `<li><a href="/traces">Traces View</a></li>`)
	if .UiLivepage {
		fmt.Fprintf(, `<li><a href="/livepage">Livepage UI</a></li>`)
	}

	if .UiMcp {
		fmt.Fprintf(, `<li>MCP: http://%s/mcp</li>`, )
	}
	fmt.Fprintf(, `</ul>`)

	fmt.Fprintf(, "<h2>--dir %s</h2><hr><ul>", .OutputDir)
	for ,  := range  {
		 := .Name()
		if .IsDir() {
			 += "/"
		}
		fmt.Fprintf(, `<li><a href="%s">%s</a></li>`, , )
	}

	fmt.Fprintf(, "</ul><hr></body></html>")
}

// newDiagHandler creates a new func serving HTML and SVGs of diagrams.
func newDiagHandler(
	 *am.Machine,  types.DiagramType,
) func( http.ResponseWriter,  *http.Request) {
	//

	return func( http.ResponseWriter,  *http.Request) {
		 := make(chan struct{})

		middleware()

		if .Method == "OPTIONS" {
			.WriteHeader(http.StatusOK)
			return
		}

		// TODO WebDiagReq
		.Add1(ss.WebReqDiag, Pass(&A{
			DiagType:           ,
			Uri:                .RequestURI,
			HttpRequest:        ,
			HttpResponseWriter: ,
			DoneChan:           ,
			Addr:               .RemoteAddr,
		}))
		// TODO timeout
		<-
	}
}

// newWsDiagHandler creates a new func handling diagram updates over WS.
func newWsDiagHandler(
	 *am.Machine,  types.DiagramType,
) func( http.ResponseWriter,  *http.Request) {
	//

	return func( http.ResponseWriter,  *http.Request) {
		middleware()

		,  := websocket.Accept(, , &websocket.AcceptOptions{
			InsecureSkipVerify: true,
		})
		if  != nil {
			.AddErrState(ss.ErrWeb, , nil)
			return
		}
		defer .Close(websocket.StatusInternalError, "internal error")
		// TODO remove?
		 := make(chan struct{})
		.Add1(ss.WebSocketDiag, Pass(&A{
			DiagType:           ,
			WebSocketConn:      ,
			HttpRequest:        ,
			HttpResponseWriter: ,
			DoneChan:           ,
			Addr:               .RemoteAddr,
		}))
		// TODO timeout
		// TODO r.Context()?
		<-
	}
}

func middleware( http.ResponseWriter) {
	// TODO add security
	// CORS
	.Header().Set("Access-Control-Allow-Origin", "*")
	.Header().Set("Access-Control-Allow-Methods",
		"POST, GET, OPTIONS, PUT, DELETE")
	.Header().Set("Access-Control-Allow-Headers",
		"Accept, Content-Type, Content-Length, Accept-Encoding, "+
			"X-CSRF-Token, Authorization")

	// cache
	.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
	.Header().Set("Pragma", "no-cache")
	.Header().Set("Expires", "0")
}

// wsDbgHandler handles dbg protocol over WS.
func wsDbgHandler(
	 http.ResponseWriter,  *http.Request,  *am.Machine,  []*fwdConn,
) {

	,  := websocket.Accept(, , &websocket.AcceptOptions{
		InsecureSkipVerify: true,
	})
	if  != nil {
		log.Printf("Upgrade error: %v", )
		return
	}
	 := websocket.NetConn(.Context(), , websocket.MessageBinary)
	AcceptConn(, , )
}