package rpc

import (
	
	
	
	
	
	
	
	
	

	
	
	amhelp 
	am 
	
)

type ClockUpdateFunc func(now am.Time, qTick uint64, machTick uint32)

// NetMachConn is a mutation interface for NetworkMachine instances.
// It's meant to be (optionally) injected by whatever creates network machines,
// so they can communicate with the server (or another source).
type NetMachConn interface {
	// TODO take event for tracing errors
	Call(ctx context.Context, method ServerMethod, args any, resp any) bool
	Notify(ctx context.Context, method ServerMethod, args any) bool
}

// NetMachInternal are internal methods of a NetworkMachine instance returned
// by the constructor.
type NetMachInternal struct {
	nm *NetworkMachine
}

func ( *NetMachInternal) (
	 am.Time,  uint64,  uint32,
) {
	.nm.updateClock(, , )
}

func ( *NetMachInternal) () {
	.nm.clockMx.Lock()
}

func ( *NetMachInternal) () {
	.nm.clockMx.Unlock()
}

// NetworkMachine is a subset of `pkg/machine#Machine` for RPC. Lacks the queue
// and other local methods. Most methods are clock-based, thus executed locally.
// NetworkMachine implements [am.Api].
//
// # Example
//
//	c.NetMach.Add1("Foo", nil)
//	<-c.NetMach.When1("Bar", nil)
type NetworkMachine struct {
	// If true, the machine will print all exceptions to stdout. Default: true.
	// Requires an ExceptionHandler binding and Machine.PanicToException set.
	LogStackTrace bool

	// internal

	// RPC client parenting this NetworkMachine. If nil, the machine is read-only
	// and won't allow for mutations / network calls.
	conn NetMachConn
	// remoteId is the ID of the remote state machine.
	remoteId string

	// net machine internal

	errInternal chan error
	// embed and reuse subscriptions
	subs     *am.Subscriptions
	id       string
	ctx      context.Context
	disposed atomic.Bool
	// Err is the last error that occurred on this netowrk instance.
	err    atomic.Pointer[error]
	schema am.Schema
	// external lock
	clockMx         sync.RWMutex
	schemaMx        sync.RWMutex
	machTime        am.Time
	machClock       am.Clock
	queueTick       uint64
	stateNames      am.S
	activeStates    atomic.Pointer[am.S]
	activeStatesDbg am.S
	// TODO indexWhenArgs
	// indexWhenArgs am.IndexWhenArgs
	whenDisposed   chan struct{}
	tracers        []am.Tracer
	tracersMx      sync.RWMutex
	handlers       []*handler
	handlersMx     sync.Mutex
	parentId       string
	tags           atomic.Pointer[[]string]
	logLevel       atomic.Pointer[am.LogLevel]
	logger         atomic.Pointer[am.LoggerFn]
	logEntriesLock sync.Mutex
	logEntries     []*am.LogEntry
	// If true, logs will start with the machine's id (5 chars).
	// Default: true.
	logId     atomic.Bool
	semLogger *semLogger
	// execQueue executed handlers and tracers
	machTick        uint32
	t               atomic.Pointer[am.Transition]
	disposeHandlers []am.HandlerDispose
	filterMutations bool
	nextHandlerNum  int
}

var ssNS = states.StateSourceStates

var _ am.Api = &NetworkMachine{}

// NewNetworkMachine creates a new instance of a NetworkMachine.
func (
	 context.Context,  string,  NetMachConn,  am.Schema,
	 am.S,  am.Api,  []string,  bool,
) (*NetworkMachine, *NetMachInternal, error) {
	//

	// validate
	if  == nil {
		return nil, nil, errors.New("ctx cannot be nil")
	}
	if  != nil && len() != len() {
		return nil, nil, errors.New(
			"schema and stateNames must have the same length",
		)
	}
	if  == nil {
		return nil, nil, errors.New("parent cannot be nil")
	}
	if  == nil {
		 = []string{states.TagRpcNetmach, states.TagKeySrcId}
	}

	 := &NetworkMachine{
		LogStackTrace: true,

		errInternal:     make(chan error, 0),
		conn:            ,
		id:              ,
		ctx:             .Context(),
		schema:          ,
		stateNames:      ,
		whenDisposed:    make(chan struct{}),
		machTime:        make(am.Time, len()),
		machClock:       am.Clock{},
		queueTick:       1,
		parentId:        .Id(),
		filterMutations: ,
	}
	.tags.Store(&)
	.logId.Store(true)
	close(.errInternal)

	// init clock
	for ,  := range  {
		.machClock[] = 0
	}
	.subs = am.NewSubscriptionManager(, .machClock,
		.is, .not, .log)
	.semLogger = &semLogger{mach: }
	 := am.LogNothing
	.logLevel.Store(&)
	.activeStates.Store(&am.S{})
	.OnDispose(func( string,  context.Context) {
		.Dispose()
	})

	// ret a priv func to update the clock of this instance
	return , &NetMachInternal{}, nil
}

// ///// RPC methods

// ///// Mutations (remote)

// Add activates a list of states in the machine, returning the result of the
// transition (Executed, Queued, Canceled).
// Like every mutation method, it will resolve relations and trigger handlers.
//
// # Example
//
//	mach.Add(am.S{"Foo", "Bar"}, nil)
//	// (Foo:1 Bar:1)
//
// # Blocking
//
// This method is blocking and waits for the remote result.
func ( *NetworkMachine) ( am.S,  am.A) am.Result {
	if .conn == nil || .disposed.Load() {
		return am.Canceled
	}

	.MustParseStates()

	// reject early
	if .filterMutations && !.mutAccepted(am.MutationAdd, ) {
		return am.Canceled
	}

	// call rpc
	 := &MsgSrvMutation{}
	 := &MsgCliMutation{
		States: amhelp.StatesToIndexes(.StateNames(), ),
		Args:   ,
	}
	if !.conn.Call(.Context(), ServerAdd, , ) {
		return am.Canceled
	}

	return .Result
}

// Add1 is a shorthand method to add a single state with the passed args.
// See Add().
//
// # Example
//
//	mach.Add1("Foo", nil)
//	// (Foo:1)
//
// # Blocking
//
// This method is blocking and waits for the remote result.
func ( *NetworkMachine) ( string,  am.A) am.Result {
	if .conn == nil || .disposed.Load() {
		return am.Canceled
	}
	return .Add(am.S{}, )
}

// AddNS is a NoSync method - an efficient way for adding states, as it
// doesn't wait for, nor transfers a response. Because of which it doesn't
// update the clock. Use Sync() to update the clock after a batch of AddNS
// calls.
func ( *NetworkMachine) ( am.S,  am.A) am.Result {
	if .conn == nil || .disposed.Load() {
		return am.Canceled
	}

	.MustParseStates()

	// reject early
	if .filterMutations && !.mutAccepted(am.MutationAdd, ) {
		return am.Canceled
	}

	// call rpc
	 := &MsgCliMutation{
		States: amhelp.StatesToIndexes(.StateNames(), ),
		Args:   ,
	}
	if !.conn.Notify(.Context(), ServerAddNS, ) {
		return am.Canceled
	}

	return am.Executed
}

// Add1NS is a single state version of AddNS.
func ( *NetworkMachine) ( string,  am.A) am.Result {
	if .conn == nil || .disposed.Load() {
		return am.Canceled
	}
	return .AddNS(am.S{}, )
}

// Remove deactivates a list of states in the machine, returning the result of
// the transition (Executed, Queued, Canceled).
// Like every mutation method, it will resolve relations and trigger handlers.
//
// # Example
//
//	mach.Remove(am.S{"Foo"}, nil)
//	// ()
//
// # Blocking
//
// This method is blocking and waits for the remote result.
func ( *NetworkMachine) ( am.S,  am.A) am.Result {
	if .conn == nil || .disposed.Load() {
		return am.Canceled
	}

	.MustParseStates()

	// reject early
	if .filterMutations && !.mutAccepted(am.MutationRemove, ) {
		return am.Canceled
	}

	// call rpc
	 := &MsgSrvMutation{}
	 := &MsgCliMutation{
		States: amhelp.StatesToIndexes(.StateNames(), ),
		Args:   ,
	}
	if !.conn.Call(.Context(), ServerRemove, , ) {
		return am.Canceled
	}

	return .Result
}

// Remove1 is [am.Machine.Remove] for a single state.
//
// # Example
//
//	mach.Remove1("Foo", nil)
//	// ()
//
// # Blocking
//
// This method is blocking and waits for the remote result.
func ( *NetworkMachine) ( string,  am.A) am.Result {
	if .conn == nil || .disposed.Load() {
		return am.Canceled
	}
	return .Remove(am.S{}, )
}

// Set deactivates a list of states in the machine, returning the result of
// the transition (Executed, Canceled, Queued).
// Like every mutation method, it will resolve relations and trigger handlers.
//
// # Example
//
//	mach.Set(am.S{"Foo"}, nil)
//	// (Foo:1)
//
// # Blocking
//
// This method is blocking and waits for the remote result.
func ( *NetworkMachine) ( am.S,  am.A) am.Result {
	if .conn == nil || .disposed.Load() {
		return am.Canceled
	}

	.MustParseStates()

	// reject early
	if .filterMutations && !.mutAccepted(am.MutationSet, ) {
		return am.Canceled
	}

	// call rpc
	 := &MsgSrvMutation{}
	 := &MsgCliMutation{
		States: amhelp.StatesToIndexes(.StateNames(), ),
		Args:   ,
	}
	if !.conn.Call(.Context(), ServerSet, , ) {
		return am.Canceled
	}

	return .Result
}

// AddErr is a dedicated method to add the StateException state with the passed
// error and optional arguments.
// Like every mutation method, it will resolve relations and trigger handlers.
// AddErr produces a stack trace of the error, if LogStackTrace is enabled.
func ( *NetworkMachine) ( error,  am.A) am.Result {
	if .conn == nil || .disposed.Load() {
		return am.Canceled
	}
	return .AddErrState(am.StateException, , )
}

// AddErrState adds a dedicated error state, along with the build in
// StateException state. Like every mutation method, it will resolve relations
// and trigger handlers. AddErrState produces a stack trace of the error, if
// LogStackTrace is enabled.
func ( *NetworkMachine) (
	 string,  error,  am.A,
) am.Result {
	if .conn == nil || .disposed.Load() ||
		 == context.Canceled {

		return am.Canceled
	}

	// keep the last err locally
	.err.Store(&)

	// log a stack trace to the local log
	if .LogStackTrace {
		 := utils.CaptureStackTrace()
		.log(am.LogChanges, nofmt.Sprintf("ERROR: %s\nTrace:\n%s", , ))
	}

	// build args
	 := am.Pass(&am.AException{
		Err: ,
	})

	 := am.S{, am.StateException}
	// mark errors added locally with ErrOnClient
	if .Has1(ssNS.ErrOnClient) {
		 = append(, ssNS.ErrOnClient)
	}

	return .Add(, am.PassMerge(, ))
}

// EvAdd is like Add, but passed the source event as the 1st param, which
// results in traceable transitions.
//
// # Blocking
//
// This method is blocking and waits for the remote result.
func ( *NetworkMachine) (
	 *am.Event,  am.S,  am.A,
) am.Result {
	if .conn == nil || .disposed.Load() {
		return am.Canceled
	}

	.MustParseStates()

	// TODO mutation filtering (req schema)

	// call rpc
	 := &MsgSrvMutation{}
	 := &MsgCliMutation{
		States: amhelp.StatesToIndexes(.StateNames(), ),
		Args:   ,
		Event:  .Export(),
	}
	if !.conn.Call(.Context(), ServerAdd, , ) {
		return am.Canceled
	}

	return .Result
}

// EvAdd1 is like Add1 but passed the source event as the 1st param, which
// results in traceable transitions.
//
// # Blocking
//
// This method is blocking and waits for the remote result.
func ( *NetworkMachine) (
	 *am.Event,  string,  am.A,
) am.Result {
	if .conn == nil || .disposed.Load() {
		return am.Canceled
	}
	return .EvAdd(, am.S{}, )
}

// TODO EvAddNS

// EvRemove1 is like Remove1, but passed the source event as the 1st param,
// which results in traceable transitions.
//
// # Blocking
//
// This method is blocking and waits for the remote result.
func ( *NetworkMachine) (
	 *am.Event,  string,  am.A,
) am.Result {
	if .conn == nil || .disposed.Load() {
		return am.Canceled
	}
	return .EvRemove(, am.S{}, )
}

// EvRemove is like Remove but passed the source event as the 1st param, which
// results in traceable transitions.
//
// # Blocking
//
// This method is blocking and waits for the remote result.
func ( *NetworkMachine) (
	 *am.Event,  am.S,  am.A,
) am.Result {
	if .conn == nil || .disposed.Load() {
		return am.Canceled
	}

	.MustParseStates()

	// TODO mutation filtering (req schema)

	// call rpc
	 := &MsgSrvMutation{}
	 := &MsgCliMutation{
		States: amhelp.StatesToIndexes(.StateNames(), ),
		Args:   ,
		Event:  .Export(),
	}
	if !.conn.Call(.Context(), ServerRemove, , ) {
		return am.Canceled
	}

	return .Result
}

// EvAddErr is like AddErr, but passed the source event as the 1st param, which
// results in traceable transitions.
//
// # Blocking
//
// This method is blocking and waits for the remote result.
func ( *NetworkMachine) (
	 *am.Event,  error,  am.A,
) am.Result {
	if .conn == nil || .disposed.Load() {
		return am.Canceled
	}
	return .EvAddErrState(, am.StateException, , )
}

// EvAddErrState is like AddErrState, but passed the source event as the 1st
// param, which results in traceable transitions.
//
// # Blocking
//
// This method is blocking and waits for the remote result.
func ( *NetworkMachine) (
	 *am.Event,  string,  error,  am.A,
) am.Result {
	if .conn == nil || .disposed.Load() ||
		 == context.Canceled {

		return am.Canceled
	}

	// keep the last err locally
	.err.Store(&)

	// log a stack trace to the local log
	if .LogStackTrace {
		 := utils.CaptureStackTrace()
		.log(am.LogChanges, nofmt.Sprintf("ERROR: %s\nTrace:\n%s", , ))
	}

	// build args
	 := am.Pass(&am.AException{
		Err: ,
	})

	 := am.S{, am.StateException}
	// mark errors added locally with ErrOnClient
	if .Has1(ssNS.ErrOnClient) {
		 = append(, ssNS.ErrOnClient)
	}

	return .EvAdd(, , am.PassMerge(, ))
}

// Toggle deactivates a list of states in case all are active, or activates
// them otherwise. Returns the result of the transition (Executed, Queued,
// Canceled).
//
// # Blocking
//
// This method is blocking and waits for the remote result.
func ( *NetworkMachine) ( am.S,  am.A) am.Result {
	if .conn == nil || .disposed.Load() {
		return am.Canceled
	}
	if .Is() {
		return .Remove(, )
	} else {
		return .Add(, )
	}
}

// Toggle1 activates or deactivates a single state, depending on its current
// state. Returns the result of the transition (Executed, Queued, Canceled).
//
// # Blocking
//
// This method is blocking and waits for the remote result.
func ( *NetworkMachine) ( string,  am.A) am.Result {
	if .conn == nil || .disposed.Load() {
		return am.Canceled
	}
	if .Is1() {
		return .Remove1(, )
	} else {
		return .Add1(, )
	}
}

// EvToggle is a traced version of [am.Machine.Toggle].
//
// # Blocking
//
// This method is blocking and waits for the remote result.
func ( *NetworkMachine) (
	 *am.Event,  am.S,  am.A,
) am.Result {
	if .conn == nil || .disposed.Load() {
		return am.Canceled
	}
	if .Is() {
		return .EvRemove(, , )
	} else {
		return .EvAdd(, , )
	}
}

// EvToggle1 is a traced version of [am.Machine.Toggle1].
//
// # Blocking
//
// This method is blocking and waits for the remote result.
func ( *NetworkMachine) (
	 *am.Event,  string,  am.A,
) am.Result {
	if .conn == nil || .disposed.Load() {
		return am.Canceled
	}
	if .Is1() {
		return .EvRemove1(, , )
	}
	return .EvAdd1(, , )
}

// ///// Checking (local)

// Is checks if all the passed states are currently active.
//
//	machine.StringAll() // ()[Foo:0 Bar:0 Baz:0]
//	machine.Add(am.S{"Foo"}, nil)
//	machine.Is(am.S{"Foo"}) // true
//	machine.Is(am.S{"Foo", "Bar"}) // false
func ( *NetworkMachine) ( am.S) bool {
	return .is()
}

// Is1 is [am.Machine.Is] for a single state.
func ( *NetworkMachine) ( string) bool {
	return .Is(am.S{})
}

func ( *NetworkMachine) ( am.S) bool {
	 := .ActiveStates(nil)
	for ,  := range .MustParseStates() {
		if !slices.Contains(, ) {
			return false
		}
	}

	return true
}

// IsErr checks if the machine has the StateException state currently active.
func ( *NetworkMachine) () bool {
	return .Is1(am.StateException)
}

// Not checks if **none** of the passed states are currently active.
//
//	machine.StringAll()
//	// -> ()[A:0 B:0 C:0 D:0]
//	machine.Add(am.S{"A", "B"}, nil)
//
//	// not(A) and not(C)
//	machine.Not(am.S{"A", "C"})
//	// -> false
//
//	// not(C) and not(D)
//	machine.Not(am.S{"C", "D"})
//	// -> true
func ( *NetworkMachine) ( am.S) bool {
	.clockMx.RLock()
	defer .clockMx.RUnlock()

	return .not()
}

func ( *NetworkMachine) ( am.S) bool {
	return utils.SlicesNone(.MustParseStates(), .ActiveStates(nil))
}

// Not1 is [am.Machine.Not] for a single state.
func ( *NetworkMachine) ( string) bool {
	return .Not(am.S{})
}

// Any is a group call to Is, returns true if any of the params return true
// from Is.
//
//	machine.StringAll() // ()[Foo:0 Bar:0 Baz:0]
//	machine.Add(am.S{"Foo"}, nil)
//	// is(Foo, Bar) or is(Bar)
//	machine.Any(am.S{"Foo", "Bar"}, am.S{"Bar"}) // false
//	// is(Foo) or is(Bar)
//	machine.Any(am.S{"Foo"}, am.S{"Bar"}) // true
func ( *NetworkMachine) ( ...am.S) bool {
	for ,  := range  {
		if .Is() {
			return true
		}
	}
	return false
}

// Any1 is group call to [am.Machine.Is1], returns true if any of the params
// return true from [am.Machine.Is1].
func ( *NetworkMachine) ( ...string) bool {
	for ,  := range  {
		if .Is1() {
			return true
		}
	}
	return false
}

// Has return true is passed states are registered in the machine. Useful for
// checking if a machine implements a specific state set.
func ( *NetworkMachine) ( am.S) bool {
	return utils.SlicesEvery(.StateNames(), )
}

// Has1 is shorthand for Has. It returns true if the passed state is
// registered in the machine.
func ( *NetworkMachine) ( string) bool {
	return .Has(am.S{})
}

// IsClock checks if the machine has changed since the passed
// clock. Returns true if at least one state has changed.
func ( *NetworkMachine) ( am.Clock) bool {
	.clockMx.RLock()
	defer .clockMx.RUnlock()

	for ,  := range  {
		if .machTime[.Index1()] !=  {
			return false
		}
	}

	return true
}

// WasClock checks if the passed time has happened (or happening right now).
// Returns false if at least one state is too early.
func ( *NetworkMachine) ( am.Clock) bool {
	.clockMx.RLock()
	defer .clockMx.RUnlock()

	for ,  := range  {
		if .machTime[.Index1()] <  {
			return false
		}
	}

	return true
}

// IsTime checks if the machine has changed since the passed
// time (list of ticks). Returns true if at least one state has changed. The
// states param is optional and can be used to check only a subset of states.
func ( *NetworkMachine) ( am.Time,  am.S) bool {
	.MustParseStates()
	.clockMx.RLock()
	defer .clockMx.RUnlock()

	 := .StateNames()
	if  == nil {
		 = 
	}

	for ,  := range  {
		if .machTime[slices.Index(, [])] !=  {
			return false
		}
	}

	return true
}

// WasTime checks if the passed time has happened (or happening right now).
// Returns false if at least one state is too early. The
// states param is optional and can be used to check only a subset of states.
func ( *NetworkMachine) ( am.Time,  am.S) bool {
	.MustParseStates()
	.clockMx.RLock()
	defer .clockMx.RUnlock()

	 := .StateNames()
	if  == nil {
		 = 
	}

	for ,  := range  {
		if .machTime[slices.Index(, [])] <  {
			return false
		}
	}

	return true
}

// Switch returns the first state from the passed list that is currently active,
// making it handy for switch statements. Useful for state groups.
//
//	switch mach.Switch(ss.GroupPlaying) {
//	case "Playing":
//	case "Paused":
//	case "Stopped":
//	}
func ( *NetworkMachine) ( ...am.S) string {
	 := .ActiveStates(nil)
	for ,  := range  {
		for ,  := range  {
			if slices.Contains(, ) {
				return 
			}
		}
	}

	return ""
}

// ///// Waiting (local)

// WhenErr returns a channel that will be closed when the machine is in the
// StateException state.
//
// ctx: optional context that will close the channel early.
//
// # Example
//
//	<-mach.WhenErr(nil)
func ( *NetworkMachine) ( context.Context) <-chan struct{} {
	return .When([]string{am.StateException}, )
}

// When returns a channel that will be closed when all the passed states
// become active or the machine gets disposed.
//
// ctx: optional context that will close the channel early.
//
// # Example
//
//	<-mach.When(am.S{"Foo", "Bar"}, nil)
func ( *NetworkMachine) (
	 am.S,  context.Context,
) <-chan struct{} {
	if .disposed.Load() {
		return .subs.Closed
	}

	// locks
	.clockMx.Lock()
	defer .clockMx.Unlock()

	return .subs.When(.MustParseStates(), )
}

// When1 is an alias to When() for a single state.
// See When.
//
// # Example
//
//	<-mach.When1("Foo", nil)
func ( *NetworkMachine) (
	 string,  context.Context,
) <-chan struct{} {
	return .When(am.S{}, )
}

// WhenNot returns a channel that will be closed when all the passed states
// become inactive or the machine gets disposed.
//
// ctx: optional context that will close the channel early.
//
// # Example
//
//	<-mach.WhenNot(am.S{"Foo"}, nil)
func ( *NetworkMachine) (
	 am.S,  context.Context,
) <-chan struct{} {
	if .disposed.Load() {
		 := make(chan struct{})
		close()
		return 
	}

	// locks
	.clockMx.Lock()
	defer .clockMx.Unlock()

	return .subs.WhenNot(.MustParseStates(), )
}

// WhenNot1 is an alias to WhenNot() for a single state.
// See WhenNot.
//
// # Example
//
//	<-mach.WhenNot1("Foo", nil)
func ( *NetworkMachine) (
	 string,  context.Context,
) <-chan struct{} {
	return .WhenNot(am.S{}, )
}

// WhenTime returns a channel that will be closed when all the passed states
// have passed the specified time. The time is a logical clock of the state.
// Machine time can be sourced from [am.Machine.Time](), or
// [am.Machine.Clock]().
//
// ctx: optional context that will close the channel early.
//
// # Example
//
//	<-mach.WhenTime(am.S{"Foo", "Bar"}, am.Time{6, 10}, nil)
func ( *NetworkMachine) (
	 am.S,  am.Time,  context.Context,
) <-chan struct{} {
	if .disposed.Load() {
		return .subs.Closed
	}

	// close early on invalid
	if len() != len() {
		 := nofmt.Errorf(
			"whenTime: states and times must have the same length (%s)",
			utils.J(),
		)
		.AddErr(, nil)

		return .subs.Closed
	}

	// locks
	.clockMx.Lock()
	defer .clockMx.Unlock()

	return .subs.WhenTime(, , )
}

// WhenTime1 waits till ticks for a single state equal the given value (or
// higher).
//
// ctx: optional context that will close the channel early.
//
// # Example
//
//	<-mach.WhenTime1("Foo", 6, nil)
func ( *NetworkMachine) (
	 string,  uint64,  context.Context,
) <-chan struct{} {
	return .WhenTime(am.S{}, am.Time{}, )
}

// WhenTicks waits N ticks of a single state (relative to now). Uses WhenTime
// underneath.
//
// ctx: optional context that will close the channel early.
//
// # Example
//
//	<-mach.WhenTicks("Foo", 2, nil)
func ( *NetworkMachine) (
	 string,  int,  context.Context,
) <-chan struct{} {
	return .WhenTime(am.S{}, am.Time{uint64() + .Tick()}, )
}

// WhenNextActive waits until the state becomes active, excluding the current
// activity.
//
// ctx: optional context that will close the channel early.
//
// # Example
//
//	<-mach.WhenNextActive("Foo", nil)
func ( *NetworkMachine) (
	 string,  context.Context,
) <-chan struct{} {
	// TODO add to API
	return .WhenTicks(, am.NextActiveIn(.Tick()), )
}

// WhenQuery returns a channel that will be closed when the passed [clockCheck]
// function returns true. [clockCheck] should be a pure function and
// non-blocking.
//
// ctx: optional context that will close the channel early.
//
// # Example
//
//	<-mach.WhenQuery(func(c am.Clock) bool {
//		// Foo activated >5 times and Bar activated twice as much
//		return c["Foo"] >= 10 && c["Bar"] >= 2*c["Foo"]
//	}, nil)
func ( *NetworkMachine) (
	 func( am.Clock) bool,  context.Context,
) <-chan struct{} {
	// locks
	.clockMx.Lock()
	defer .clockMx.Unlock()

	return .subs.WhenQuery(, )
}

// WhenQueue waits until the passed queueTick gets processed.
//
// # Example
//
//	<-mach.WhenQueue(mach.Add1("Foo", nil))
func ( *NetworkMachine) ( am.Result) <-chan struct{} {
	// locks
	.clockMx.Lock()
	defer .clockMx.Unlock()

	// finish early
	if .queueTick >= uint64() {
		return .subs.Closed
	}

	return .subs.WhenQueue()
}

// WhenTimeSum waits till machine time equals the given value (or higher).
//
// ctx: optional context that will close the channel early.
//
// # Example
//
//	<-mach.WhenTimeSum(16, nil)
func ( *NetworkMachine) (
	 uint64,  context.Context,
) <-chan struct{} {
	//

	if .disposed.Load() {
		return .subs.Closed
	}

	// close early on too late
	if  <= .Time(nil).Sum(nil) {
		return .subs.Closed
	}

	// locks
	.clockMx.Lock()
	defer .clockMx.Unlock()

	return .subs.WhenTimeSum(, )
}

// ///// Waiting (remote)

// WhenArgs returns a channel that will be closed when the passed state
// becomes active with all the passed args. ArgsBase are compared using
// the native
// '=='. It's meant to be used with async Multi states, to filter out
// a specific call.
//
// ctx: optional context that will close the channel when handler loop ends.
//
// # Example
//
//	<-mach.WhenArgs("Foo", am.A{"ID": 123}, nil)
func ( *NetworkMachine) (
	 string,  am.A,  context.Context,
) <-chan struct{} {
	// TODO subscribe on the source via a uint8 token
	return .subs.Closed
}

// ///// Getters (remote)

// Err returns the last error.
func ( *NetworkMachine) () error {
	 := .err.Load()
	if  == nil {
		return nil
	}
	return *
}

// ///// Getters (local)

// StateNames returns a SHARED copy of all the state names.
func ( *NetworkMachine) () am.S {
	.schemaMx.Lock()
	defer .schemaMx.Unlock()

	return slices.Clone(.stateNames)
}

// ActiveStates returns a copy of the currently active states when states is
// nil, optionally limiting the results to a subset of states.
func ( *NetworkMachine) ( am.S) am.S {
	 := *.activeStates.Load()
	if  == nil {
		return slices.Clone()
	}

	 := make(am.S, 0, len())
	for ,  := range  {
		if slices.Contains(, ) {
			 = append(, )
		}
	}

	return 
}

// Tick return the current tick for a given state.
func ( *NetworkMachine) ( string) uint64 {
	.clockMx.RLock()
	defer .clockMx.RUnlock()

	return .tick()
}

func ( *NetworkMachine) ( string) uint64 {
	.MustParseStates(am.S{})
	return .machClock[]
}

// Clock returns current machine's clock, a state-keyed map of ticks. If states
// are passed, only the ticks of the passed states are returned.
func ( *NetworkMachine) ( am.S) am.Clock {
	.clockMx.RLock()
	defer .clockMx.RUnlock()
	 := .StateNames()

	if  == nil {
		 = 
	}

	 := am.Clock{}
	for ,  := range  {
		[] = .machClock[]
	}

	return 
}

// Time returns machine's time, a list of ticks per state. Returned value
// includes the specified states, or all the states if nil.
func ( *NetworkMachine) ( am.S) am.Time {
	.clockMx.RLock()
	defer .clockMx.RUnlock()

	return .time()
}

func ( *NetworkMachine) ( am.S) am.Time {
	 := .StateNames()
	if  == nil {
		 = 
	}

	 := am.Time{}
	for ,  := range  {
		 := slices.Index(, )
		 = append(, .machTime[])
	}

	return 
}

// NewStateCtx returns a new sub-context, bound to the current clock's tick of
// the passed state.
//
// Context cancels when the state has been deactivated, or right away,
// if it isn't currently active.
//
// State contexts are used to check state expirations and should be checked
// often inside goroutines.
//
// [e]: optional [am.Event] to bind to this context.
func ( *NetworkMachine) (
	 string,  ...*am.Event,
) context.Context {
	.clockMx.Lock()
	defer .clockMx.Unlock()

	var  am.Time
	if os.Getenv(am.EnvAmDebug) != "" {
		 = .time(nil)
	}

	if  := am.OptEv();  != nil {
		return am.EvToCtx(.subs.NewStateCtx(, ), )
	}

	return .subs.NewStateCtx(, )
}

// ///// MISC

// Log logs an [extern] message unless LogNothing is set.
// Optionally redirects to a custom logger from [SemLogger.SetLogger].
func ( *NetworkMachine) ( string,  ...any) {
	.log(am.LogExternal, , ...)
}

// SemLogger returns the semantic logger of the machine
func ( *NetworkMachine) () am.SemLogger {
	return .semLogger
}

// StatesVerified returns true if the state names have been ordered
// using VerifyStates.
func ( *NetworkMachine) () bool {
	return true
}

// Context returns the machine's context. This context lives longer than
// the parent context and allows for graceful shutdown. This is the context
// which should be used to create submachines. See also
// [am.Machine.DisposeTimeout].
func ( *NetworkMachine) () context.Context {
	return .ctx
}

// ContextParent returns the original context passed to the constructor.
func ( *NetworkMachine) () context.Context {
	return .ctx
}

// Id returns the machine's id.
func ( *NetworkMachine) () string {
	return .id
}

// RemoteId returns the ID of the remote state machine.
func ( *NetworkMachine) () string {
	return .remoteId
}

// ParentId returns the ID of the parent machine (if any).
func ( *NetworkMachine) () string {
	return .parentId
}

// Tags returns machine's tags, a list of unstructured strings without spaces.
func ( *NetworkMachine) () []string {
	 := .tags.Load()
	if  == nil {
		return nil
	}
	return slices.Clone(*)
}

// SetTags updates the machine's tags with the provided slice of strings.
func ( *NetworkMachine) ( []string) {
	 = slices.Clone()
	.tags.Store(&)
	.semLogger.SetTags()
}

// String returns a one line representation of the currently active states,
// with their clock values. Inactive states are omitted.
// Eg: (Foo:1 Bar:3)
func ( *NetworkMachine) () string {
	.clockMx.RLock()
	defer .clockMx.RUnlock()

	 := .StateNames()
	 := .ActiveStates(nil)
	 := "("
	for ,  := range  {
		if !slices.Contains(, ) {
			continue
		}

		if  != "(" {
			 += " "
		}
		 := slices.Index(, )
		 += nofmt.Sprintf("%s:%d", , .machTime[])
	}

	return  + ")"
}

// StringAll returns a one line representation of all the states, with their
// clock values. Inactive states are in square brackets.
//
//	(Foo:1 Bar:3) [Baz:2]
func ( *NetworkMachine) () string {
	.clockMx.RLock()
	defer .clockMx.RUnlock()

	 := .StateNames()
	 := .ActiveStates(nil)
	 := "("
	 := "["
	for ,  := range  {
		 := slices.Index(, )

		if slices.Contains(, ) {
			if  != "(" {
				 += " "
			}
			 += nofmt.Sprintf("%s:%d", , .machTime[])
			continue
		}

		if  != "[" {
			 += " "
		}
		 += nofmt.Sprintf("%s:%d", , .machTime[])
	}

	return  + ") " +  + "]"
}

// Inspect returns a multi-line string representation of the machine (states,
// relations, clocks).
// states: param for ordered or partial results.
func ( *NetworkMachine) ( am.S) string {
	.clockMx.RLock()
	defer .clockMx.RUnlock()

	 := .StateNames()
	if  == nil {
		 = 
	}

	 := .ActiveStates(nil)
	 := ""
	for ,  := range  {

		 := .schema[]
		 := "0"
		if slices.Contains(, ) {
			 = "1"
		}

		 := slices.Index(, )
		 += nofmt.Sprintf("%s %s\n"+
			"    |Tick     %d\n", , , .machTime[])
		if .Auto {
			 += "    |Auto     true\n"
		}
		if .Multi {
			 += "    |Multi    true\n"
		}
		if .Add != nil {
			 += "    |Add      " + utils.J(.Add) + "\n"
		}
		if .Require != nil {
			 += "    |Require  " + utils.J(.Require) + "\n"
		}
		if .Remove != nil {
			 += "    |Remove   " + utils.J(.Remove) + "\n"
		}
		if .After != nil {
			 += "    |After    " + utils.J(.After) + "\n"
		}
	}

	return 
}

func ( *NetworkMachine) ( am.LogLevel,  string,  ...any) {
	if .semLogger.Level() <  {
		return
	}

	 := ""
	if .logId.Load() {
		 := .id
		if len() > 5 {
			 = [:5]
		}
		 = "[" +  + "] "
		 =  + 
	}

	 := nofmt.Sprintf(, ...)
	 := .semLogger.Logger()
	if  != nil {
		(, , ...)
	} else {
		nofmt.Println()
	}

	.logEntriesLock.Lock()
	defer .logEntriesLock.Unlock()

	.logEntries = append(.logEntries, &am.LogEntry{
		Level: ,
		Text:  ,
	})
}

// MustParseStates parses a list of states, panicking on
// states which are not defined for the machine, and removing duplicates.
func ( *NetworkMachine) ( am.S) am.S {
	.schemaMx.Lock()
	defer .schemaMx.Unlock()

	// check if all states are defined in m.Schema
	for ,  := range  {
		if !slices.Contains(.stateNames, ) {
			panic(nofmt.Sprintf("state %s is not defined for %s (via %s)", ,
				.remoteId, .id))
		}
	}

	return utils.SlicesUniq()
}

// Index1 returns the index of a state in the machine's StateNames() list, or -1
// when not found or machine has been disposed.
func ( *NetworkMachine) ( string) int {
	return slices.Index(.StateNames(), )
}

// Index returns a list of state indexes in the machine's StateNames() list,
// with -1s for missing ones.
func ( *NetworkMachine) ( am.S) []int {
	 := make([]int, len())
	for ,  := range  {
		[] = .Index1()
	}

	return 
}

// Dispose disposes the machine and all its emitters. You can wait for the
// completion of the disposal with `<-mach.WhenDisposed()`. It's advised to use
// Dispose() func from pkg/helpers instead, which handles Disposed state mixing.
func ( *NetworkMachine) () {
	if !.disposed.CompareAndSwap(false, true) {
		return
	}

	// tracers
	.tracersMx.Lock()
	defer .tracersMx.Unlock()
	for ,  := range .tracers {
		.MachineDispose(.id)
	}

	// run doDispose handlers
	// TODO timeouts?
	for ,  := range .disposeHandlers {
		(.id, .ctx)
	}

	utils.CloseSafe(.whenDisposed)

	// TODO push remotely?
}

// IsDisposed returns true if the machine has been disposed.
func ( *NetworkMachine) () bool {
	return .disposed.Load()
}

// WhenDisposed returns a channel that will be closed when the machine is
// disposed.
func ( *NetworkMachine) () <-chan struct{} {
	return .whenDisposed
}

// Export exports the machine state as Serialized: ID, machine time, and
// state names.
func ( *NetworkMachine) () (*am.Serialized, am.Schema, error) {
	.clockMx.RLock()
	defer .clockMx.RUnlock()
	.schemaMx.RLock()
	defer .schemaMx.RUnlock()

	.log(am.LogChanges, "[import] exported at %d ticks", .time(nil))

	return &am.Serialized{
		ID:          .id,
		Time:        .time(nil),
		StateNames:  .StateNames(),
		MachineTick: .machTick,
		QueueTick:   .queueTick,
	}, .schema.Clone(), nil
}

// Schema returns a copy of machine's schema.
func ( *NetworkMachine) () am.Schema {
	return .schema
}

// HandlersBindMaps is like [am.Machine.HandlersBind] but accepts maps of
// handlers to bypass reflecting structs. It may lead to higher performance.
// Returns a binding ID.
func ( *NetworkMachine) (
	 map[string]am.HandlerNegotiation,
	 map[string]am.HandlerFinal,  ...am.BindOpts,
) (string, error) {
	.handlersMx.Lock()
	defer .handlersMx.Unlock()

	 := optBindOpts()
	// TODO name from stack trace
	 := "anon" + amhelp.RandId(4)
	if .Id != "" {
		 = idRe.ReplaceAllString(.Id, "")
	}

	 := .newHandlerMap(, )
	.id = 
	.num = .nextHandlerNum
	.opts = &
	.nextHandlerNum++
	.handlers = append(.handlers, )
	.log(am.LogOps, "[handlers] bind %d:%s", .num, )

	return , nil
}

// newHandlerMap creates a map-based [handler] binding.
func ( *NetworkMachine) (
	 map[string]am.HandlerNegotiation,
	 map[string]am.HandlerFinal,
) *handler {
	return &handler{
		isMap:        true,
		finals:       ,
		negotiations: ,
	}
}

// handleMap runs a map-based pipe handler. Must be called with h.mx locked.
func ( *NetworkMachine) (
	 *handler, ,  string,  *am.Event,  string,
) {
	 :=  + 

	var  am.HandlerFinal
	var  am.HandlerNegotiation
	if  == am.SuffixState ||  == am.SuffixEnd {
		 = .finals[]
	} else {
		 = .negotiations[]
	}
	if  == nil &&  == nil {
		return
	}

	.log(am.LogOps, "[handler:%d] %s", .num, )

	 := .t.Load()
	for  := range .tracers {
		.tracers[].HandlerStart(, , )
	}
	if  != nil {
		()
	} else {
		()
	}
	for  := range .tracers {
		.tracers[].HandlerEnd(, , )
	}
}

// TODO move
// optBindOpts will return the first [BindOpts] from a list.
func optBindOpts( []am.BindOpts) am.BindOpts {
	if len() > 0 {
		return [0]
	}
	return am.BindOpts{}
}

// TODO move
var idRe = regexp.MustCompile(`[^a-zA-Z0-9-_]+`)

// Handlers returns the IDs of bound handlers.
func ( *NetworkMachine) () []string {
	// TODO lock, support id
	// w.handlersLock.Lock()
	// defer w.handlersLock.Unlock()

	 := make([]string, 0, len(.handlers))
	for ,  := range .handlers {
		 = append(, .id)
	}

	return 
}

// HandlersDetach detaches previously bound machine handlers.
func ( *NetworkMachine) ( string) error {
	 := .handlers

	for ,  := range  {
		if .id ==  {
			.handlers = utils.SlicesWithout(, )
			// TODO
			// h.dispose()

			return nil
		}
	}

	return errors.New("handlers not bound")
}

// BindHandlers is deprecated, use [am.Api.HandlersBind].
func ( *NetworkMachine) ( any,
	 ...am.BindOpts,
) (string, error) {
	return .HandlersBind(, ...)
}

// DetachHandlers is deprecated, use [am.Api.HandlersDetach].
func ( *NetworkMachine) ( string) error {
	return .()
}

// TracerBind binds a Tracer to the machine. Tracers can cause StateException in
// submachines, before any handlers are bound. Use the Err() getter to examine
// such errors.
//
// # NetworkMachine
//
// NetworkMachine tracers cannot mutate synchronously, as network machines
// don't have a queue and WILL deadlock when nested.
func ( *NetworkMachine) ( am.Tracer) (string, error) {
	.tracersMx.Lock()
	defer .tracersMx.Unlock()

	 := reflect.ValueOf()
	if .Kind() != reflect.Pointer || .Elem().Kind() != reflect.Struct {
		return "", errors.New("BindTracer expects a pointer to a struct")
	}

	.tracers = append(.tracers, )
	.log(am.LogOps, "[tracers] bind %s", .TracerId())

	return .TracerId(), nil
}

// TracerDetach tries to remove a tracer from the machine. Returns an error in
// case the tracer wasn't bound.
func ( *NetworkMachine) ( string) error {
	.tracersMx.Lock()
	defer .tracersMx.Unlock()

	for ,  := range .tracers {
		if .TracerId() ==  {
			// TODO check
			.tracers = slices.Delete(.tracers, , +1)
			.log(am.LogOps, "[tracers] detach %s", )

			return nil
		}
	}

	return errors.New("tracer not bound")
}

// BindTracer is deprecated, use [NetworkMachine.TracerBind].
func ( *NetworkMachine) ( am.Tracer) (string, error) {
	return .TracerBind()
}

// DetachTracer is deprecated, use [NetworkMachine.TracerDetach].
func ( *NetworkMachine) ( string) error {
	return .TracerDetach()
}

// Tracers return a copy of currently attached tracers.
func ( *NetworkMachine) () []am.Tracer {
	.clockMx.Lock()
	defer .clockMx.Unlock()

	return slices.Clone(.tracers)
}

// updateClock updates the clock of this NetworkMachine and requires a locked
// clockMx, which is then unlocked by this method.
func ( *NetworkMachine) (
	 am.Time,  uint64,  uint32,
) {
	// TODO require mutType and called states for SyncAllMutations and handlers

	.tracersMx.Lock()
	defer .tracersMx.Unlock()

	 := .machTime
	 := maps.Clone(.machClock)

	 := .ActiveStates(nil)
	 := am.S{}
	 := .StateNames()
	for ,  := range  {
		if am.IsActiveTick([]) {
			 = append(, )
		}
	}
	 = .activateRequired()
	 := am.StatesDiff(, )
	 := am.StatesDiff(, )

	 := &am.Transition{
		MachApi: ,
		Id:      utils.RandId(8),

		TimeBefore: ,
		TimeAfter:  ,
		Mutation: &am.Mutation{
			// TODO use add and remove when all ticks passed
			Type:   am.MutationSet,
			Called: .Index(),
			Args:   nil,
			IsAuto: false,
		},
		LogEntries:    .logEntries,
		TargetIndexes: .Index(),
	}
	.IsCompleted.Store(true)
	.IsSettled.Store(true)
	// TODO may not be true for qTicks-only updates
	.IsAccepted.Store(true)
	.t.Store()
	.logEntries = nil

	// call tracers
	for ,  := range .tracers {
		.TransitionInit()
	}
	for ,  := range .tracers {
		.TransitionStart()
	}

	// set active states
	.machTime = 
	for ,  := range .machTime {
		.machClock[[]] = 
	}
	.machTick = 
	// the local queue ticks later than the new one, all queue subs are invalid
	if .queueTick >  {
		.log(am.LogOps, "[queueTick] flushing (%d to %s)", .queueTick, )
		.queueFlush()
	}
	.queueTick = 
	.activeStates.Store(&)
	.activeStatesDbg = 

	// handlers
	.processHandlers(, )

	// unlock for tracers (always locked by the caller)
	.clockMx.Unlock()

	for ,  := range .tracers {
		// TODO dbg tracing doesnt show up in the UI?
		.TransitionEnd()
	}

	// subscriptions
	.processSubscriptions(, , )
	.t.Store(nil)
}

// activateRequired will fake required states (when not all synced and
// schema present)
func ( *NetworkMachine) ( am.S) am.S {
	// skip for schema-less netmachs
	if .schema == nil {
		return 
	}

	// locks
	.schemaMx.RLock()
	defer .schemaMx.RUnlock()

	 := slices.Clone()
	 := make(map[string]bool)
	var  func(string)
	 = func( string) {
		if ![] {
			[] = true
			for ,  := range .schema[].Require {
				 = append(, )
				()
			}
		}
	}

	// recurse on all the active states
	for ,  := range  {
		()
	}

	return utils.SlicesUniq()
}

func ( *NetworkMachine) ( bool) []*handler {
	if ! {
		.handlersMx.Lock()
		defer .handlersMx.Unlock()
	}

	return slices.Clone(.handlers)
}

func ( *NetworkMachine) (,  am.S) {
	// no changes
	if len()+len() == 0 {
		return
	}

	for ,  := range .getHandlers(false) {
		if  == nil {
			continue
		}

		// TODO ensure multi states covered
		for ,  := range  {
			.handle(, , , am.SuffixState)
		}
		for ,  := range  {
			.handle(, , , am.SuffixEnd)
		}

		// global handler
		.handle(, , am.StateAny, am.SuffixState)
	}
}

func ( *NetworkMachine) (
	,  am.S,  am.Clock,
) {
	// lock
	.clockMx.RLock()

	// collect
	 := .subs.ProcessStateCtx(, )
	 := slices.Concat(
		.subs.ProcessWhen(, ),
		.subs.ProcessWhenTime(),
		.subs.ProcessWhenTimeSum(),
		.subs.ProcessWhenQueue(.queueTick),
		.subs.ProcessWhenQuery(),
	)

	// unlock
	.clockMx.RUnlock()

	// close outside the critical zone
	for ,  := range  {
		()
	}
	for ,  := range  {
		close()
	}
}

// AddBreakpoint1 is a single state version of [am.Machine.AddBreakpoint].
func ( *NetworkMachine) (
	 string,  string,  bool,
) {
	// TODO
}

// AddBreakpoint adds a breakpoint for an outcome of mutation (added and
// removed states) checked by mutation equality. Once such a mutation happens,
// a log message will be printed out. We can set an IDE's breakpoint on this
// line and see the mutation's sync stack trace. If
// [am.Machine.LogStackTrace] is set, the stack trace will be printed out as
// well. Many breakpoints can be added, but none removed.
//
// Breakpoints are useful to find the caller of a mutation, but don't work with
// [am.Machine.Set].
//
// strict: strict skips already active / inactive (for strict of diff equality).
func ( *NetworkMachine) (
	 am.S,  am.S,  bool,
) {
	// TODO
}

// Groups returns the machine's state groups as indexes, along with the
// group order. See [am.Machine.SetGroups].
func ( *NetworkMachine) () (map[string][]int, []string) {
	// TODO maybe sync along with schema?
	return nil, nil
}

// CanAdd checks if [states] can be added and returns Executed or
// [AT.CheckDone] if a dry run mutation passes. Useful for reducing failed
// negotiations.
func ( *NetworkMachine) ( am.S,  am.A) am.Result {
	// TODO check relations
	return am.Executed
}

// CanAdd1 is [am.Machine.CanAdd] for a single state.
func ( *NetworkMachine) ( string,  am.A) am.Result {
	// TODO check relations
	return am.Executed
}

// CanRemove checks if [states] can be removed and returns Executed or
// [AT.CheckDone] if a dry run mutation passes. Useful for reducing failed
// negotiations.
func ( *NetworkMachine) ( am.S,  am.A) am.Result {
	// TODO check relations
	return am.Executed
}

// CanRemove1 is [am.Machine.CanRemove] for a single state.
func ( *NetworkMachine) ( string,  am.A) am.Result {
	// TODO check relations
	return am.Executed
}

// Transition returns the current transition, if any.
func ( *NetworkMachine) () *am.Transition {
	return .t.Load()
}

// IsLocal returns true for *am.Machine and false for *arpc.NetworkMachine.
func ( *NetworkMachine) () bool {
	return false
}

// ErrInternal returns a channel which receives handler and eval timeout errors,
// so they can be handled accordingly without passing through mutations.
// This method always returns a closed channel for [am.Api.IsLocal] == false.
func ( *NetworkMachine) () <-chan error {
	return .errInternal
}

// QueueLen returns the number of mutations currently in the queue.
//
// # NetworkMachine
//
// Always returns 0, outbound throttling is not implemented.
func ( *NetworkMachine) () uint16 {
	// TODO implement outbound throttling
	return 0
}

func ( *NetworkMachine) () {
	.subs.QueueFlush()
}

// QueueTick is the number of times the queue has processed a mutation. Starts
// from [1], for easy comparison with [Result].
func ( *NetworkMachine) () uint64 {
	.clockMx.RLock()
	defer .clockMx.RUnlock()

	return .queueTick
}

// MachineTick is the number of times the machine has been started. Each start
// means an empty queue. Only set by [am.Machine.Import].
func ( *NetworkMachine) () uint32 {
	.clockMx.RLock()
	defer .clockMx.RUnlock()

	return .machTick
}

// ActivatedAt returns the machine time of the last activation of the passed
// state (even if the state isnt currently active).
//
// # NetworkMachine
//
// Not implemented yet, panics.
func ( *NetworkMachine) ( string) uint64 {
	// TOOD copy test
	if .disposed.Load() {
		return 0
	}
	panic("not implemented yet")
}

// ParseStates parses a list of states, removing unknown ones and duplicates.
// Use [am.Machine.Has] and [am.Machine.Has1] to check if a state is defined
// for the machine.
func ( *NetworkMachine) ( am.S) am.S {
	.schemaMx.Lock()
	defer .schemaMx.Unlock()

	// check if all states are defined in the schema
	 := make(map[string]struct{})
	 := false
	for  := range  {
		if ,  := .schema[[]]; ! {
			continue
		}
		if ,  := [[]]; ! {
			[[]] = struct{}{}
		} else {
			// mark as duplicated
			 = true
		}
	}

	if  {
		return utils.SlicesUniq()
	}
	return slices.Collect(maps.Keys())
}

// OnDispose adds a function to be called after the machine gets disposed.
// These functions will run synchronously just before WhenDisposed() channel
// gets closed. Considering it's a low-level feature, it's advised to handle
// disposal via dedicated states.
func ( *NetworkMachine) ( am.HandlerDispose) {
	.handlersMx.Lock()
	defer .handlersMx.Unlock()

	.disposeHandlers = append(.disposeHandlers, )
}

func ( *NetworkMachine) (
	 am.MutationType,  am.S,
) bool {
	if .schema == nil {
		return true
	}

	// TODO adapt [am.RelationsResolver] to filter here
	return true
}

// debug
// func (w *NetworkMachine) QueueDump() []string {
// 	return nil
// }